【问题标题】:Silverlight async api's cause hangs and none-responsivenessSilverlight 异步 api 导致挂起和无响应
【发布时间】:2010-02-03 15:46:49
【问题描述】:

此代码导致 silverlight 挂起。如果我删除 ManualResetEvent 代码,什么都不会发生

        private ManualResetEvent mre = new ManualResetEvent(false);

        ...

        WebClient sender = new WebClient();
        sender. += new OpenReadCompletedEventHandler(this.ReadComplete);
        sender.OpenReadAsync(new Uri(this.url+"?blob="+BODY, UriKind.Relative));

        mre.WaitOne();

    }
    public bool T = false;
    public void ReadComplete(object sender, OpenReadCompletedEventArgs e)
    {

        mre.Set();
    }

【问题讨论】:

  • 很难对这个问题做出明智的回答,它缺乏细节。你在下载什么?下载后你在做什么?
  • 没有什么可下载的

标签: silverlight synchronization webclient silverlight-3.0


【解决方案1】:

您不能在 UI 线程中阻塞(参见“mre.WaitOne”)。如果您绝对需要 WaitOne,则必须在单独的线程中运行您的代码。这可以按如下方式完成:

var t = new Thread(delegate()
{
    //...
    mre.WaitOne();
    //...
});

人们会期望回调中的“mre.Set()”会被触发。但是,我也遇到了同样的问题,所以显然,OpenReadAsync 回调机制使用 UI 线程作为中间调度程序。该调度无法发生,它正在等待设置事件。

【讨论】:

  • 好的,我现在正在使用线程,ui没有挂起,但是仍然没有webclient连接,ui没有更新,当我调试时显示没有异常... ..怎么了?
  • “ui 没有更新”:当我看到这个症状时,问题是我在 Application.UnhandledException 的实现中忽略了异常。在那里调用 Debugger.Break() 可能会有所帮助。
  • 你收到 ReadComplete() 回调了吗?
【解决方案2】:

我认为只有几个原因可能会让您相信您需要这种阻塞等待。要么你不知道你应该在完整事件中继续你的代码,要么你有其他本地状态,你没有包含在你的示例代码中,ReadCompleted 过程无权访问。

这里是一些用于处理下载流的样板代码:-

string dummy = "Some value"; // local value you still need to access when download complete

WebClient wc = new WebClient();
wc.OpenReadCompleted += (s, args)
{
   if (!args.Cancelled)
   {
     try
     {
         Stream stream = args.Stream;  // This is the data you are after
         // Do stuff with stream, note the dummy variable is still accessible here.
     }
     catch (Exception err)
     {
         //Do something sensible with the exception to make sure its surfaced
     }
   }
};
sender.OpenReadAsync(new Uri(this.url+"?blob="+BODY, UriKind.Relative));

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多