引用马克·格雷韦尔的话:
///...blah blah updating files
string newText = "abc"; // running on worker thread
this.Invoke((MethodInvoker)delegate {
someLabel.Text = newText; // runs on UI thread
});
///...blah blah more updating files
我正在使用WPF进行此操作,因此无法使用
invoke
方法。有什么想法吗?这些Threading的东西正在:/更多详细信息
我像这样开始我的新主题
Thread t = new Thread (LoopThread);
t.Start();
t.Join();
但是在整个
LoopThread
中,我想写到UI。更新
感谢Jon Skeet的
Dispatcher.Invoke
位。似乎MethodInvoker
也是WinForms。相当于WPF?更新2
感谢Adriano使用
System.Windows.Forms.MethodInvoker
建议而不是System.Action
。(你们对
this
参数的混淆是正确的,只需要进行构建以消除错误。)自从添加
SimpleInvoke
以来,现在我被Extension method must be defined in a non-generic static class
在线上
public partial class MainWindow : Window
有什么想法吗?
最佳答案
在WPF中,您只需要使用 Dispatcher.Invoke
而不是Control.Invoke
即可。DispatcherObject
类(WPF类派生自该类)公开了 Dispatcher
属性,因此您只需要:
Dispatcher.Invoke((Action) delegate {
someLabel.Text = newText; // runs on UI thread
});
如果您使用的是C#3或更高版本(以及.NET 3.5或更高版本),则可能要向
DispatcherObject
添加扩展方法:// Make this a new top-level class
public static class DispatcherObjectExtensions
{
public static void SimpleInvoke(this DispatcherObject dispatcherObject,
Action action)
{
dispatcherObject.Dispatcher.Invoke(action);
}
}
因此,您可以使用:
// From within your UI code
this.SimpleInvoke(() => someLabel.Text = newText);
关于c# - 多线程调用代理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11136999/