如何在.With循环(Httpwebrequest)中使用dispatcher.BeginInvoke每个dispatcher.BeginInvoke在调用另一个dispatcher.BeginInvoke之前都已完成。因为httpwerequest返回的对象的位置错误。
发布于 2011-09-15 16:29:00
不,BeginInvoke是异步的-您基本上是将委托添加到要在UI线程上执行的项的队列中。
如果在后台线程中继续工作之前,您需要等待委托执行完毕,那么您需要自己做一些工作,因为Silverlight不支持同步Dispatcher.Invoke方法或DispatcherOperation.Wait()方法。Silverlight试图避免这样的同步方法--如果你可以重新设计你的代码,这样你就不需要等待了,那将是更好的选择。
发布于 2011-09-15 20:39:42
能够轻松地将同步操作序列转换为异步代码一直是我在博客中讨论的一个话题。如果你想采用我的方法,你需要添加以下(相对较小的)代码块:
以下是一些示例代码,具有您在问题中所描述的风格:
IEnumerable<AsyncOperation> LoadSomeStuff(IList<string> urls)
{
for (string url in urls)
{
yield return AsyncOperationService.SwitchToBackgroundThread();
WebRequest req = WebRequest.Create(url);
WebResponse resp = null;
yield return req.GetResponseAsyncOp(r => resp = r);
using (resp)
{
// Do stuff with the Web Response such as construct model class instances from a stream.
}
// When ready to actually start touching the UI
yield return AsyncOperationService.SwitchToUIThread();
// Do stuff to the UI
}
}用法:
List<string> urls = new List<string> {"pinkElephants.xml", "whileElephants.xml"}
LoadSomeStuff(urls).Run(err =>
{
if (err == null)
{
// Cool, it all worked and I probably don't need to do anything
}
else
{
// Something bad happened, lets tell the user about it in the UI somehow.
}
});请注意,这不是最有效的代码。然而,在许多情况下,发送大量HTTP响应所花费的时间远远超过了其余代码所消耗的时间,因此效率低下的情况可能非常小,并且非常值得降低代码的复杂性。
https://stackoverflow.com/questions/7427866
复制相似问题