How to call wcf service Asynchronously

I think the best way is to convert the APM pattern into the Task pattern, using 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);
    }
}

Usage:

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

Leave a Comment