如何异步调用wcf服务

Tho*_*mas 2 .net c# wcf asynchronous

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

[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);
   }
Run Code Online (Sandbox Code Playgroud)

nos*_*tio 10

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

public static class WcfExt
{
    public static Task<int> 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

IAddTwoNumbers service = CreateWcfClientProxy();
int result = await service.AddAsync(a, b);
Run Code Online (Sandbox Code Playgroud)