如果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);
}
答案 0 :(得分:10)
我认为最好的方法是convert the APM pattern into the Task pattern,使用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);
}
}
用法:
IAddTwoNumbers service = CreateWcfClientProxy();
int result = await service.AddAsync(a, b);
答案 1 :(得分:0)
没有异步有线通信模式,WFC也不例外。通过电线进行异步需要对服务和合同进行根本性更改。具体而言,您的合同必须是双向合同,并且必须将“结束”从服务推送到客户端以及结果。换句话说,通过线路,'async'成为回调。