【发布时间】:2023-03-27 08:34:01
【问题描述】:
我一直在尝试实现多类线程 GUI 管理。正如在我希望不同的线程分布在不同的 .cs 文件中的多个类中,以根据需要更新 UI。
我搜索了 stackoverflow 和其他来源,发现大多数人使用 Dispatcher.Invoke 或类似的东西。所以我决定开始测试......
所以下面是一个名为 wThread.cs 的类中的一个线程,
public class wThread
{
public EventHandler SignalLabelUpdate;
public Dispatcher uiUpdate;
public wThread()
{
uiUpdate = Program.myForm.dispat;
//the uiUpdate seems to be null for some reason... If i am doing it wrong how do i get the dispatcher?
Thread myThread = new Thread(run);
myThread.Start();
}
Action myDelegate = new Action(updateLabel);
// is there a way i can pass a string into the above so updatelabel will work?
public void updateLabel(String text)
{
if (SignalLabelUpdate != null)
SignalLabelUpdate(this, new TextChangedEvent(text));
}
public void run()
{
while (uiUpdate == null)
Thread.Sleep(500);
for (int i = 0; i < 1000; i++)
{
//I hope that the line below would work
uiUpdate.BeginInvoke(new Action(delegate() { Program.myForm.label1.Text = "count at " + i; }));
// was also hoping i can do the below commented code
// uiUpdate.Invoke(myDelegate)
Thread.Sleep(1000);
}
}
}
下面是我的 form1.cs,它是 Visual Studio 2012 的预加载代码,
public partial class Form1 : Form
{
public Dispatcher dispat;
public Form1()
{
dispat = Dispatcher.CurrentDispatcher;
InitializeComponent();
wThread worker = new wThread();
}
}
我的大部分问题都在上面的 cmets 中,但这里列出了它们:
-
由于某种原因,uiUpdate 似乎为空...如果我做错了,我该如何获取调度程序? (wThread.cs 问题)
uiUpdate = Program.myForm.dispat' -
有没有办法我可以将字符串传递到上面,以便 updatelabel 可以工作?
Action myDelegate = new Action(updateLabel); -
我希望下面的行能正常工作
uiUpdate.BeginInvoke(new Action(delegate() { Program.myForm.label1.Text = "count at " + i; })); -
也希望我能做下面的注释代码
uiUpdate.Invoke(myDelegate)
编辑:我将 wThread 构造函数 wThread worker = new wThread() 移出 form1 初始化区域......它修复了我的空指针。相反,我将 wThread 构造函数移动到构造表单的静态 main void 中......比如 Application.Run(myForm);
不幸的是,在我关闭 UI 之前 wThread 不会启动。对此最好的办法是什么?在 Application.Run 启动我的表单之前创建另一个线程并使用该线程启动我的真实线程?
【问题讨论】:
-
您使用的是什么 UI 技术?我看到 Dispatcher 和 Form? WinForms 还是 WPF?
-
实现后台线程工作的最简单方法是使用 MVVM(假设您在 WPF 中):stackoverflow.com/a/2034333/1561465
标签: c# multithreading user-interface