我一直在试图实现多类线程GUI管理。由于我希望不同的线程在不同的.cs文件中的多个类中传播,以根据需要更新UI。NullReferenceException @ Dispatcher和其他GUI问题
我已经搜索了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();
}
}
我的大部分问题在上述意见,但这里有他们列出:
的由于某种原因,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 =新的wThread()out of form1初始化区域...并且它修复了我的空指针。相反,我将wThread构造函数移动到构造窗体的静态主void中,就像Application.Run(myForm);
不幸的是,wThread不会启动,直到我关闭用户界面..什么是最好的事情要做到这一点?在Application.Run启动我的Form并使用该线程启动我的真实线程之前创建另一个线程?
你使用的是什么UI技术?我看到调度员和表格? WinForms或WPF? – bic 2014-12-10 21:48:09
在后台线程上实现工作的最简单方法是使用MVVM(假设你在WPF中):http://stackoverflow.com/a/2034333/1561465 – 2014-12-10 21:49:40