我构建了一个测试箱来学习有关 Windows 窗体应用程序中的线程的知识。 Silverlight 和 Java 提供了 Dispatcher,这在更新时非常有用 GUI 元素。
代码示例: 声明类委托(delegate)
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);
}
}
委派文本框更新
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 });
非常感谢, 雷伊特
最佳答案
在很多这样的情况下,最简单的方法是使用“捕获变量”在线程之间传递状态;这意味着您可以将逻辑本地化:
public void UpdateTestBox(string newText)
{
BeginInvoke((MethodInvoker) delegate {
tb_output.Text = newText;
});
}
如果我们期望它在工作线程上被调用,上面的代码特别有用(检查 InvokeRequired
的意义不大)——请注意,这对于 UI 来说都是安全的或工作线程,并允许我们在线程之间传递尽可能多或尽可能少的状态。
关于c# - C# 中委托(delegate)语法的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/906057/