Silverlight异步API导致挂起和无响应
此代码会导致 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();
}
this code causes silverlight to hang. If I remove the ManualResetEvent code, nothing happens
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能阻塞 UI 线程(参见“mre.WaitOne”)。如果您绝对需要 WaitOne,则必须在单独的线程中运行代码。这可以按如下方式完成:
人们期望回调中的“mre.Set()”将被触发。但是,我遇到了同样的问题,所以显然,OpenReadAsync 回调机制使用 UI 线程作为中间调度程序。该调度无法发生,它正在等待事件设置。
You cannot block in the UI thread (cf. "mre.WaitOne"). If you absolutely need the WaitOne, you must run your code in a separate thread. This can be done as follows:
One would expect that the "mre.Set()" in the callback would be triggered. However, I've had the same problem, so apparently, the OpenReadAsync callback mechanism uses the UI thread as intermediate dispatcher. That dispatching cannot happen it is waiting for the event to be set.
我认为只有几个原因可能会让您相信您需要这种阻塞等待。您可能不知道应该在完成事件中继续使用您的代码,或者您有其他未包含在
ReadCompleted
过程无权访问的示例代码中的本地状态。这是一些用于处理下载流的样板代码:-
There are only couple of reasons that I can see that might lead you believe you need this blocking wait. Either you are not aware that you should continue with your code in the complete event or you have other local state that you haven't included in your sample code that the
ReadCompleted
procedure doesn't have access to.Here is some boiler plate code for handling a downloaded stream:-