C#中的委托语法问题

我构建了一个Testbox来了解Windows窗体应用程序中的线程。 Silverlight和Java提供了Dispatcher,它在更新GUI元素时非常有用。

代码示例:声明类代表

public delegate void d_SingleString(string newText); 

创建线程

  _thread_active = true; Thread myThread = new Thread(delegate() { BackGroundThread(); }); myThread.Start(); 

线程function

  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

在许多情况下,最简单的方法是使用“捕获变量”在线程之间传递状态; 这意味着您可以保持逻辑本地化:

 public void UpdateTestBox(string newText) { BeginInvoke((MethodInvoker) delegate { tb_output.Text = newText; }); } 

如果我们希望在工作线程上调用它(检查InvokeRequired点数InvokeRequired ),上面特别有用 – 请注意,这对UI或工作线程都是安全的,并且允许我们在两者之间传递尽可能多的状态。线程。

对于像这样的简单委托,您可以使用框架中的Action委托( 链接到msdn )。

 public void UpdateTestBox(string newText) { if (InvokeRequired) { BeginInvoke(new Action(UpdateTestBox), new object[] { newText }); return; } tb_output.Text = newText; } 

这样您就不需要维护自己的委托声明了。