0

我需要进行两次 wcf 调用来构建模型

[SecurityOperationBehavior]
public Response1 Func1(Request1 req)
{
}


[SecurityOperationBehavior]
public Response2 Func2(Request2 req)
{
}

我知道我需要使用 TaskCompletionSource 来等到两个调用都完成。

public FullResult GetResult(int id)
{
  Request1 req = new Request1 ();
  req.id = id;

  Request2 req2 = new Request2 ();
  req2.id = id;

  var taskCompletions = new[]
                         {
                            new TaskCompletionSource<object>(),
                            new TaskCompletionSource<object>()

                           };
 var tasks = new[] { taskCompletions[0].Task, taskCompletions[1].Task  };

  System.Threading.Tasks.Task.Factory.StartNew(()=>Func1(req );
  System.Threading.Tasks.Task.Factory.StartNew(()=>Func2(req2 );

  System.Threading.Tasks.Task.WaitAll(tasks);

   //the following is what I want to do. The results of the 
   //two service calls will be contained in the the full result

    FullResult  result = new FullResult();

   result.first = tasks[0].Result;
   result.second = tasks[0].Result;

   return Result;



}

问题:

两个服务调用完成后如何设置结果?

4

1 回答 1

3

这里根本不需要任务完成源。只需等待结果Task.StartNew

public FullResult GetResult(int id)
{
    Request1 req = new Request1();
    req.id = id;

    Request2 req2 = new Request2();
    req2.id = id;

    var tasks = new Task[] {
        Task.Factory.StartNew(() => Func1(req))
        , Task.Factory.StartNew(() => Func2(req2))};

    System.Threading.Tasks.Task.WaitAll(tasks);

    FullResult result = new FullResult();

    result.first = tasks[0];
    result.second = tasks[1];

    return result;
}
于 2013-02-12T17:06:20.257 回答