2010-08-05 121 views
0

在我的silverlight頁面中,當用戶單擊一個按鈕時;該應用程序調用3個Web服務異步。它必須等待這3個異步調用完成,或者必須在這些調用完成時得到通知。這3個調用完成後,結果將寫入文本文件(這是一個具有較高信任度的瀏覽器外應用程序)。 除了寫一個計時器並輪詢這些呼叫外,有沒有更好的方式在呼叫完成時得到通知?調用3個Web服務異步並等待它們完成

回答

0

當您調用webservice調用時,您傳入一個回調 - 因此您會在通話完成時自動收到通知。

要跟蹤完成情況,可以使用beginXXX調用的'object asyncState'參數來跟蹤每個調用,或者可以使用遞增/遞減計數整數。

試試這個:http://msdn.microsoft.com/en-us/library/cc197937(v=VS.95).aspx

2

的反應擴展(Rx)的圖書館是爲這個完美的。看看這裏:

http://www.jaylee.org/post/2010/06/22/WP7Dev-Using-the-WebClient-with-Reactive-Extensions-for-Effective-Asynchronous-Downloads.aspx

滾動至底部。以下是等待兩個網絡客戶端下載的示例,只需替換您的電話號碼即可:

public IObservable<string> StartDownload(string uri) 
{ 
    WebClient wc = new WebClient(); 

    var o = Observable.FromEvent<DownloadStringCompletedEventArgs>(wc, "DownloadStringCompleted") 

         // Let's make sure that we're not on the UI Thread 
         .ObserveOn(Scheduler.ThreadPool) 

         // When the event fires, just select the string and make 
         // an IObservable<string> instead 
         .Select(newString => ProcessString(newString.EventArgs.Result)); 

    wc.DownloadStringAsync(new Uri(uri)); 

    return o; 
} 

public string ProcessString(string s) 
{ 
    // A very very very long computation 
    return s + "<!-- Processing End -->"; 
} 

public void DisplayMyString() 
{ 
    var asyncDownload = StartDownload("http://bing.com"); 
    var asyncDownload2 = StartDownload("http://google.com"); 

    // Take both results and combine them when they'll be available 
    var zipped = asyncDownload.Zip(asyncDownload2, (left, right) => left + " - " + right); 

    // Now go back to the UI Thread 
    zipped.ObserveOn(Scheduler.Dispatcher) 

      // Subscribe to the observable, and set the label text 
      .Subscribe(s => myLabel.Text = s); 
}