Silverlight 异步调用3个web服务,并等待它们完成
在我的silverlight页面中,当用户单击按钮时;该应用程序将3个web服务称为异步。它必须等待这3个异步调用完成,或者在这些调用完成时收到通知。完成这3个调用后,结果将写入文本文件(这是一个信任度提升的浏览器外应用程序)。Silverlight 异步调用3个web服务,并等待它们完成,silverlight,service,call,asynchronous,Silverlight,Service,Call,Asynchronous,在我的silverlight页面中,当用户单击按钮时;该应用程序将3个web服务称为异步。它必须等待这3个异步调用完成,或者在这些调用完成时收到通知。完成这3个调用后,结果将写入文本文件(这是一个信任度提升的浏览器外应用程序)。 除了编写计时器和轮询这些调用外,还有更好的方法在调用完成时收到通知吗?当调用webservice调用时,您会传入回调,这样在调用完成时会自动收到通知 要跟踪完成情况,可以使用beginXXX调用的“object asyncState”参数跟踪每个调用,也可以使用向上/向
除了编写计时器和轮询这些调用外,还有更好的方法在调用完成时收到通知吗?当调用webservice调用时,您会传入回调,这样在调用完成时会自动收到通知 要跟踪完成情况,可以使用beginXXX调用的“object asyncState”参数跟踪每个调用,也可以使用向上/向下计数整数 试试这个:反应式扩展(Rx)库非常适合这种情况。请看这里: 滚动到底部。下面是一个等待两次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);
}
public IObservable StartDownload(字符串uri)
{
WebClient wc=新的WebClient();
var o=可观察的FromEvent(wc,“DownloadStringCompleted”)
//让我们确保我们不在UI线程上
.ObserveOn(Scheduler.ThreadPool)
//当事件激发时,只需选择字符串并使
//一个IObservable替代
.Select(newString=>ProcessString(newString.EventArgs.Result));
DownloadStringAsync(新Uri(Uri));
返回o;
}
公共字符串ProcessString(字符串s)
{
//非常长的计算
返回s+“”;
}
public void DisplayMyString()
{
var asynchdownload=StartDownload(“http://bing.com");
var asyncDownload2=开始下载(“http://google.com");
//将这两个结果合并在一起
var zipped=asyncDownload.Zip(asyncDownload2,(左、右)=>left+“-”+right);
//现在回到UI线程
zipped.ObserveOn(Scheduler.Dispatcher)
//订阅observable,并设置标签文本
.Subscribe(s=>myLabel.Text=s);
}