我构建了一个Testbox来了解Windows窗体应用程序中的线程。 Silverlight和Java提供了Dispatcher,它在更新时非常有用 GUI元素。
代码示例: 声明类代表
public delegate void d_SingleString(string newText);
创建线程
_thread_active = true;
Thread myThread = new Thread(delegate() { BackGroundThread(); });
myThread.Start();
线程功能
private void BackGroundThread()
{
while (_thread_active)
{
MyCounter++;
UpdateTestBox(MyCounter.ToString());
Thread.Sleep(1000);
}
}
委派TextBox更新
public void UpdateTestBox(string newText)
{
if (InvokeRequired)
{
BeginInvoke(new d_SingleString(UpdateTestBox), new object[] { newText });
return;
}
tb_output.Text = newText;
}
有没有办法在BeginInvoke方法中声明Delate声明?!
类似
BeginInvoke(*DELEGATE DECLARATION HERE*, new object[] { newText });
非常感谢, rAyt
答案 0 :(得分:9)
在这种情况下,最简单的方法是使用“捕获变量”在线程之间传递状态;这意味着您可以保持逻辑本地化:
public void UpdateTestBox(string newText)
{
BeginInvoke((MethodInvoker) delegate {
tb_output.Text = newText;
});
}
如果我们期望在工作线程上调用它(这么少点检查InvokeRequired
),上面特别有用 - 请注意,这对于UI或工作线程都是安全的,并允许我们在线程之间传递尽可能多的状态。
答案 1 :(得分:4)
对于像这样的简单代表,您可以使用框架中的Action<T>
委托(link to msdn)。
public void UpdateTestBox(string newText)
{
if (InvokeRequired)
{
BeginInvoke(new Action<string>(UpdateTestBox), new object[] { newText });
return;
}
tb_output.Text = newText;
}
这样您就不需要维护自己的委托声明了。