首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用dispatcher

如何使用dispatcher
EN

Stack Overflow用户
提问于 2011-09-15 16:22:16
回答 2查看 547关注 0票数 1

如何在.With循环(Httpwebrequest)中使用dispatcher.BeginInvoke每个dispatcher.BeginInvoke在调用另一个dispatcher.BeginInvoke之前都已完成。因为httpwerequest返回的对象的位置错误。

EN

回答 2

Stack Overflow用户

发布于 2011-09-15 16:29:00

不,BeginInvoke是异步的-您基本上是将委托添加到要在UI线程上执行的项的队列中。

如果在后台线程中继续工作之前,您需要等待委托执行完毕,那么您需要自己做一些工作,因为Silverlight不支持同步Dispatcher.Invoke方法或DispatcherOperation.Wait()方法。Silverlight试图避免这样的同步方法--如果你可以重新设计你的代码,这样你就不需要等待了,那将是更好的选择。

票数 3
EN

Stack Overflow用户

发布于 2011-09-15 20:39:42

能够轻松地将同步操作序列转换为异步代码一直是我在博客中讨论的一个话题。如果你想采用我的方法,你需要添加以下(相对较小的)代码块:

  • The core AsyncOperationService
  • Code to create an AsyncOperation from the .NET Async Pattern
  • A couple of Extension methods for WebRequest

以下是一些示例代码,具有您在问题中所描述的风格:

代码语言:javascript
复制
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

    }

}

用法:

代码语言:javascript
复制
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响应所花费的时间远远超过了其余代码所消耗的时间,因此效率低下的情况可能非常小,并且非常值得降低代码的复杂性。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7427866

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档