调用3个Web服务异步,并等待它们完成

时间:2010-08-05 14:48:41

标签: silverlight service call asynchronous

在我的silverlight页面中,当用户点击按钮时;该应用程序,调用3个Web服务异步。它必须等待这3个异步调用完成,或者必须在完成这些调用时得到通知。完成这3个调用后,结果将写入文本文件(这是一个具有提升信任的浏览器外应用程序)。 除了编写计时器和轮询这些呼叫之外,还有更好的方法可以在呼叫完成时收到通知吗?

2 个答案:

答案 0 :(得分:2)

Reactive Extensions(Rx)库非常适合这种情况。看看这里:

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

滚动到底部。这是一个等待两个Web客户端下载的示例,只需替换您在此处调用逻辑的任何内容:

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

答案 1 :(得分:0)

当您调用网络服务电话时,您会传入回叫 - 这样您就会在通话结束时自动收到通知。

要跟踪完成情况,您可以使用beginXXX调用的'object asyncState'参数来跟踪每个调用,也可以使用向上/向下计数的整数。

试试这个:http://msdn.microsoft.com/en-us/library/cc197937(v=VS.95).aspx