如何异步调用wcf服务

如果wcf服务设计如下,那么请指导我如何从客户端Asynchronously调用Add()函数。 谢谢

 [ServiceContract] public interface IAddTwoNumbers { // If the asynchronous method pair // appears on the client channel, the client can call // them asynchronously to prevent blocking. [OperationContract (AsyncPattern=true)] IAsyncResult BeginAdd(int a, int b, AsyncCallback cb, AsyncState s); [OperationContract] int EndAdd(IAsyncResult r); // This is a synchronous version of the BeginAdd/EndAdd pair. // It appears in the client channel code by default. [OperationContract] int Add(int a, int b); } 

我认为最好的方法是使用Task.Factory.FromAsync 将APM模式转换为任务模式 :

 public static class WcfExt { public static Task AddAsync(this IAddTwoNumbers service, int a, int b) { return Task.Factory.FromAsync( (asyncCallback, asyncState) => service.BeginAdd(a, b, asyncCallback, asyncState), (asyncResult) => service.EndAdd(asyncResult), null); } } 

用法:

 IAddTwoNumbers service = CreateWcfClientProxy(); int result = await service.AddAsync(a, b); 

没有异步有线通信模式,WFC也不例外。 通过电线进行异步同步需要对服务和合同进行根本性的更改。 具体而言,您的合同必须是双向合同,并且必须将“结束”从服务推送到客户端以及结果。 换句话说,通过线路,’async’成为回调。