gpt4 book ai didi

c# - 多线程调用委托(delegate)

转载 作者:太空宇宙 更新时间:2023-11-03 20:24:56 25 4
gpt4 key购买 nike

引用 Marc Gravell 的话:

///...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 方法。有什么想法吗?这个线程的东西让我头疼:/

更多细节

我的新线程是这样开始的

Thread t = new Thread (LoopThread);
t.Start();
t.Join();

但在整个 LoopThread 中,我想写入 UI。

更新

感谢 Jon Skeet 提供的 Dispatcher.Invoke 位。似乎 MethodInvoker 也是 WinForms。等效于 WPF?

更新 2

感谢 Adriano 建议使用 System.Action 而不是 System.Windows.Forms.MethodInvoker

(关于 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属性(property),所以你只需要:

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# - 多线程调用委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11136999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com