从后台线程更新 UI
这只是一个好奇的问题。哪一种是从另一个线程更新 UI 的最佳方法。首先,这个:
private delegate void MyDelegateMethod();
void MyMethod()
{
if (unknowncontrol.InvokeRequired)
{
this.BeginInvoke(new MyDelegateMethod(MyMethod));
return;
}
unknowncontrol.property = "updating!";
}
另一方面:
Invoke((System.Threading.ThreadStart)delegate()
{
unknowncontrol.property = "updating!";
});
或者,有更好的方法吗?
当然这是针对 WinForms 的,对于 WPF 则有调度程序。 WPF的代码是怎样的?
我问的是,因为过去我在使用上述两个选项从引发的事件更新 UI 时遇到了错误。类似这样的错误:“没有可用的源代码”。我想我们所有人都见过它们:D。
谢谢,祝你有美好的一天!
This is just a curious question. Which one is the best way to update UI from another thread. First, this one:
private delegate void MyDelegateMethod();
void MyMethod()
{
if (unknowncontrol.InvokeRequired)
{
this.BeginInvoke(new MyDelegateMethod(MyMethod));
return;
}
unknowncontrol.property = "updating!";
}
On the other hand:
Invoke((System.Threading.ThreadStart)delegate()
{
unknowncontrol.property = "updating!";
});
Or, is there a better way to do this?
Of course this is for WinForms, for WPF there's the dispatcher. How is the code for WPF?
I'm asking, 'cause, in the past I experienced errors when updating UI from a raised event using both of the options above. The kind of error like: "there is no source code available". I assume all of us have seen them :D.
Thanks, and have a nice day!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
查看 Roy Osherove 的博客文章:http://osherove.com/blog/2006/3/1/the-3-ways-to-create-a-thread-safe-gui-with-net-20-with-one。 html
Check out Roy Osherove's blog post on this: http://osherove.com/blog/2006/3/1/the-3-ways-to-create-a-thread-safe-gui-with-net-20-with-one.html
我通常使用第一个模型,但这只是因为我发现它更清晰。两者之间实际上并不存在有效的区别。
I typically used the first model, but that's only because I found it clearer. There isn't really going to be an effective difference between the two.
我认为最好的方法是设置 ui 元素的属性绑定到的 CLR 属性。
As i see it the best way is to set a CLR-property to which the ui-element's property is bound to.
第一个方法 (BeginInvoke) 确保 UI 更新代码在创建控件的同一线程上执行。第二种方法则不然。让所有 UI 更新代码在同一线程上执行可以避免大量线程问题,并允许您使用不一定是线程安全的控件。
The first method (BeginInvoke) ensures that the UI update code executes on the same thread that created the control. The 2nd method does not. Having all UI updating code execute on the same thread avoids alot of threading issues and allows you to use controls that are not necessarily thread-safe.
默认的 Action delegate 在 90% 的时间内都可以工作:
The default Action delegate worked 90% of the time:
使用 [Dispatcher.Invoke(DispatcherPriority, Delegate)]< /a> 从另一个线程或后台更改 UI。
第 1 步。使用以下命名空间
第 2 步。将以下行放在需要更新 UI 的位置
Use [Dispatcher.Invoke(DispatcherPriority, Delegate)] to change the UI from another thread or from background.
Step 1. Use the following namespaces
Step 2. Put the following line where you need to update UI