从后台线程更新界面 [英] Update UI from background Thread
问题描述
这只是一个好奇的问题。哪一个是从另一个线程更新UI的最佳方式。首先,这一个:
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!";
}
在另一方面:
Invoke((System.Threading.ThreadStart)delegate()
{
unknowncontrol.property = "updating!";
});
或者,是否有更好的方法来做到这一点?
Or, is there a better way to do this?
当然,这是的WinForms,为WPF有调度。如何是WPF代码?
Of course this is for WinForms, for WPF there's the dispatcher. How is the code for WPF?
我要问,因为,在过去,我同时使用上述选项从引发的事件更新UI时经历的错误。那种像错误:没有可用的源代码。我想我们所有的人都看到他们。:D
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!
推荐答案
看看罗伊Osherove的博客文章在这:的 http://osherove.com/blog/2006/3/1/the-3-ways-to-create -a线程安全的 - 桂 - 用网-20与 - 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
delegate void Func<T>(T t);
Func del = delegate
{
// UI Code goes here
};
Invoke(del);
这篇关于从后台线程更新界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!