2013-02-12 138 views
0

我需要对堆积2 WCF调用模型如何等待异步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; 



} 

问题:

如何设置两个服务电话后的结果完成了吗?

+0

首先,你几乎肯定不希望把'里面开始新_absClient.QueryAlarmAsync'。您不需要在另一个线程中启动异步任务。其次,'QueryAlarmAsync'的签名是什么?它是否返回任务,它是否接受回调,请求对象是否有触发事件或回调属性?在异步操作完成时需要有一些通知您的机制。 – Servy 2013-02-12 16:52:19

+0

因此,基于你的编辑,是'Func1'和'Func2'长时间运行*阻塞*操作? – Servy 2013-02-12 16:54:49

+0

@Servy,对不起,我需要拨打Func1和Func2。更新了问题。请重新阅读。 – Jimmy 2013-02-12 16:55:11

回答

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; 
}