2014-01-31 209 views
2

如果wcf服務設計如下方式,請引導我如何從客戶端調用Add()函數Asynchronously。感謝如何異步調用wcf服務

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

回答

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); 
+0

我熟悉APM,但沒有任務,但想知道你在這裏使用asyncCallback函數引用,但是當你調用AddAsync()時,你不會發送asyncCallback函數參考....爲什麼? – Mou

+0

@Mou,'asyncCallback'將由'FromAsync'的Framework實現在內部提供,當它調用我的lambda時。 – Noseratio

0

有作爲異步有線通信模式沒有這樣的事,和WFC也不例外。跨線異步要求對您的服務和合同進行根本性更改。具體而言,您的合同必須是雙向合同,並且必須將「最終」從服務推送到客戶端,以及結果。換句話說,跨越線路的'異步'成爲回調。