引用马克·格雷韦尔的话:

///...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/

10-12 03:58