从另一个线程更新标签

Ant*_*nio 19 c# multithreading winforms

我在另一个类中使用一个线程来更新标签.标签是Winform Main类中的内容.

 Scanner scanner = new Scanner(ref lblCont);
 scanner.ListaFile = this.listFiles;
 Thread trd = new Thread(new ThreadStart(scanner.automaticScanner));
 trd.IsBackground = true;
 trd.Start();
 while (!trd.IsAlive) ;
 trd.Join();
Run Code Online (Sandbox Code Playgroud)

你怎么看,我将标签的引用传递给第二类的构造函数.在第二个类(扫描仪)中,我有一个名为"automaticScanner"的方法,它应该使用以下代码更新标签:

public Scanner(ref ToolStripStatusLabel _lblContatore)
{
        lblCounter= _lblContatore;
}
Thread threadUpdateCounter = new Thread(new ThreadStart(this.UpdateCounter));
threadUpdateCounter.IsBackground = true;
threadUpdateCounter.Start();
while (!threadUpdateCounter .IsAlive) ;
threadUpdateCounter.Join();

private void AggiornaContatore()
{
  this.lblCounter.Text = this.index.ToString();        
}
Run Code Online (Sandbox Code Playgroud)

我在更新标签时收到此错误:

跨线程操作无效:从创建它的线程以外的线程访问控制'Main'

我使用.net 4和Winform C#.

非常感谢您的回答.

新闻:问题是这一行:

trd.Join();
Run Code Online (Sandbox Code Playgroud)

这行阻止我的GUI和标签不更新.有一些方法可以控制线程的完成并更新标签直到结束?谢谢

Igo*_*goy 47

您无法从UI线程以外的任何其他线程更新UI.使用它来更新UI线程上的线程.

 private void AggiornaContatore()
 {         
     if(this.lblCounter.InvokeRequired)
     {
         this.lblCounter.BeginInvoke((MethodInvoker) delegate() {this.lblCounter.Text = this.index.ToString(); ;});    
     }
     else
     {
         this.lblCounter.Text = this.index.ToString(); ;
     }
 }
Run Code Online (Sandbox Code Playgroud)

请仔细阅读本章以及本书中的更多内容,以获得有关线程的清晰图片:

http://www.albahari.com/threading/part2.aspx#_Rich_Client_Applications


Hab*_*bib 11

使用MethodInvoker更新其他线程中的标签文本.

private void AggiornaContatore()
{
    MethodInvoker inv = delegate 
    {
      this.lblCounter.Text = this.index.ToString(); 
    }

 this.Invoke(inv);
}
Run Code Online (Sandbox Code Playgroud)

您收到错误是因为您的UI线程持有标签,并且由于您尝试通过另一个线程更新它,因此您将获得跨线程异常.

您还可以看到:Windows窗体中的线程