2012-04-27 29 views
0

我正在尋找使用新的async關鍵字在Silverlight中調用Web服務的示例。尋找在Silverlight中使用異步調用Web服務的示例?

這是我想要轉換的代碼:你有目標版本.NET 4.5重新生成您的服務代碼

var client = new DashboardServicesClient("BasicHttpBinding_IDashboardServices", App.DashboardServicesAddress); 
client.SelectActiveDealsCompleted += (s, e) => m_Parent.BeginInvoke(() => RefreshDealsGridComplete(e.Result, e.Error)); 
client.SelectActiveDealsAsync(); 

回答

0

。然後您可以使用async關鍵字。寫一些像這樣的代碼:

var client = new DashboardServicesClient("BasicHttpBinding_IDashboardServices", App.DashboardServicesAddress); 
// Wait here until you get the result ... 
var result = await client.SelectActiveDealsAsync(); 
// ... then refresh the ui synchronously. 
RefreshDealsGridComplete(result); 

或者你使用ContinueWith了Methode:

var client = new DashboardServicesClient("BasicHttpBinding_IDashboardServices", App.DashboardServicesAddress); 
// Start the call ... 
var resultAwaiter = client.SelectActiveDealsAsync(); 
// ... and define, what to do after finishing (while the call is running) ... 
resultAwaiter.ContinueWith(async task => RefreshDealsGridComplete(await resultAwaiter)); 
// ... and forget it 
+0

沒有工作,我仍然只看到非基於任務的版本。此外,「服務參考設置」對話框還可以選擇「生成基於任務的操作」灰顯。 – 2012-05-02 23:53:44

1

您隨時可以自己動手:

static class DashboardServicesClientExtensions 
{ 
    //typeof(TypeIDontKnow) == e.Result.GetType() 
    public static Task<TypeIDontKnow>> SelectActiveDealsTaskAsync() 
    { 
     var tcs = new TaskCompletionSource<TypeIDontKnow>(); 

     client.SelectActiveDealsCompleted += (s, e) => m_Parent.BeginInvoke(() => 
     { 
      if (e.Erorr != null) 
       tcs.TrySetException(e.Error); 
      else 
       tcs.TrySetResult(e.Result); 
     }; 
     client.SelectActiveDealsAsync(); 

     return tcs.Task; 
    } 
}; 

// calling code 
// you might change the return type to Tuple if you want :/ 
try 
{ 
    // equivalent of e.Result 
    RefreshDealsGridComplete(await client.SelectActiveDealsTaskAsync(), null); 
} 
catch (Exception e) 
{ 
    RefreshDealsGridComplete(null, e); 
}