Law*_*nce 11 c# multithreading
我需要帮助设置/更改我的C#程序中的标签的值,每当我尝试它时发生错误,说我需要交叉线程.任何人都可以编写一些代码来帮助我吗?我的代码是:
int number = 0;
int repeats = Convert.ToInt32(textBox2.Text);
while (number < repeats)
{
   repeats++;
   label5.Text = "Requested" + repeats + "Times";
}
谁能帮我?谢谢.
Jar*_*Par 34
请尝试以下更新值
label5.Invoke((MethodInvoker)(() => label5.Text = "Requested" + repeats + "Times"));
Invoke方法(from Control.Invoke)将导致传入的委托在给定Control的关联的线程上运行.在这种情况下,它将使它在您的应用程序的GUI线程上运行,从而使更新安全.
Mic*_*ael 10
你可以添加我经常使用的这种扩展方法(技术上类似于@JaredPar的答案):
  /// <summary>
  /// Extension method that allows for automatic anonymous method invocation.
  /// </summary>
  public static void Invoke(this Control c, MethodInvoker mi)
  {
     c.Invoke(mi);
     return;
  }
然后,您可以通过以下方式在代码中本地使用任何Control(或衍生物):
// "this" is any control (commonly the form itself in my apps)  
this.Invoke(() => label.Text = "Some Text");
您还可以通过匿名方法传递执行多个方法:
this.Invoke
(
   () =>
   {
      // all processed in a single call to the UI thread
      label.Text = "Some Text";
      progressBar.Value = 5;
   }
);
请记住,如果你的线程试图在一个被处理的控件上调用,你将得到一个ObjectExposedException.如果应用程序正在关闭某个线程尚未中止,则会发生这种情况.您可以通过包围Invoke()调用来"吃掉"ObjectDisposedException,也可以在Invoke()方法扩展中"吃掉"异常.