2012-10-12 42 views
1

異步CTP非常好用。 我看到了一些windows phone的例子,全部使用:
(程序集AsyncCtpLibrary_Phone.dll,v2.0.50727,AsyncCtpExtensions)。如何在VS 2010中使用WPF中的WCF進行異步等待?

var client = new WebClient(); 
string data = await client.DownloadStringTaskAsync(new Uri(url)); 

或類似上面的代碼。

如何使用async/await方法來處理我的服務? (WCF)
今天所有方法以這種方式工作:

service.MyRequestCompleted += service_myRequestCompleted; 
    service.MyRequestAsync(); 

我不能找到一種方法來使用服務的擴展方法。

+0

我發現這篇關於等待異步函數的文章。像魅力一樣工作,而且非常有效。看看這篇文章:http://blogs.msdn.com/b/ptorr/archive/2011/07/12/background-agents-part-2-of-3.aspx在這裏下載代碼:[http:/ /blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-18-51-05/BackgroundAgentDemo.zip](http://blogs.msdn.com/cfs-file。 ashx/__ key/communityserver-components-postattachments/00-10-18-51-05/BackgroundAgentDemo.zip) – Brandsdal

回答

4

偏偏,我還沒有發現它推廣任何事件的好方法,但它很容易適應這個特定事件:

public static Task WhenRequestCompleted(MyService service) //can make it an extension method if you want. 
{ 
    TaskCompletionSource<object> tcs = new TaskCompletionSource<object>(); 

    service.MyRequestCompleted +=() => //change parameter list to fit the event's delegate 
     { 
      tcs.SetResult(null); 
     }; 
    service.MyRequestAsync(); 

    return tcs.Task; 
} 

然後,你可以這樣做:

await WhenRequestCompleted(service); 
//code that runs after the request is completed. 

我假設你看到這裏的模式,所以你可以適應這個,以便它可以與其他類型的其他事件一起工作。

哦,如果事件有對你特別重要的參數,那麼你可以讓這個返回的Task<T>而不是Task和而不是使用tcs.SetResult(null)你可以使用lambda來設置結果的參數之一。

+0

Argh,打我吧,只是使用TaskCompletionSource輸入相同的方法。我想知道他們是如何回填許多舊的.Net API來支持任務。 – BFree

+0

看起來不錯,但是是酷刑有q指定事件=(有其他方式,也許? –

+0

你期望寫什麼?我看不出你怎麼能比這裏少得多 – Servy

0

它已經有一段時間,因爲我已經對WP7的工作,所以我要去假設客戶端代理必須爲每個合同法兩種EAP端點(*Async + *Completed)和APM端點(Begin* + End*) 。

如果這是正確的,那麼你可以使用TaskFactory.FromAsync包裹Begin*/End*方法,因爲這樣的:

[ServiceContract] 
public interface ICalculator 
{ 
    [OperationContract] 
    uint Divide(uint numerator, uint denominator); 
} 

static class Program 
{ 
    // Wrap those Begin/End methods into a Task-based API. 
    public static Task<uint> DivideAsyncTask(this CalculatorClient client, 
     uint numerator, uint denominator) 
    { 
    return Task<uint>.Factory.FromAsync(client.BeginDivide, client.EndDivide, 
     numerator, denominator, null); 
    } 

    static async Task CallCalculator() 
    { 
    var proxy = new CalculatorClient(); 
    var task = proxy.DivideAsyncTask(10, 5); 
    var result = await task; 
    Console.WriteLine("Result: " + result); 
    } 

    static void Main(string[] args) 
    { 
    try 
    { 
     CallCalculator().Wait(); 
    } 
    catch (Exception ex) 
    { 
     Console.Error.WriteLine(ex); 
    } 

    Console.ReadKey(); 
    } 
} 

你可能有興趣在我的博客文章async WCF today and tomorrow之一 - 不幸的是,WP7還停留在「今日」模式。在VS2012不在的時候,Async CTP很快就會被放棄。

+0

我嘗試過這樣的事情,但WP7無法做到。方法(開始/結束)默認情況下不存在,您不能使用ChannelFactory。 –