从另一个线程更新标签

时间:2013-02-15 07:52:41

标签: 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();

如何看,我将标签的引用传递给第二类的构造函数。 在第二类(扫描仪)中,我有一个名为“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();        
}

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

  

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

我使用.net 4和Winform C#。

非常感谢您的回答。

新闻: 问题是这一行:

trd.Join();

这行阻止了我的GUI,标签没有更新。 有一些方法可以控制线程的完成并更新标签直到结束? 感谢

3 个答案:

答案 0 :(得分:46)

您无法从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(); ;
     }
 }

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

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

答案 1 :(得分:10)

使用MethodInvoker更新其他帖子中的标签文字。

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

 this.Invoke(inv);
}

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

您可能还会看到:Threading in Windows Forms

答案 2 :(得分:3)

相关问题