Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update label from another thread [duplicate]

Tags:

I use a thread writing in another class for update a label. The label is contents in Winform Main class.

 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(); 

How you can see, i pass the reference of label into constructor of the second class. In the second class(Scanner) i've a method called "automaticScanner" that should update the label with this code:

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();         } 

I've receive this error on update of label:

Cross-thread operation not valid: Control 'Main' accessed from a thread other than the thread it was created on

I use .net 4 with Winform C#.

Thanks a lot for answers.

News: The problem is this line:

trd.Join(); 

This line block my GUI and the lable was not update. There are methods to control the finish of thread and updating the label until the end? Thanks

like image 705
Antonio Avatar asked Feb 15 '13 07:02

Antonio


1 Answers

You cannot update UI from any other thread other than the UI thread. Use this to update thread on the UI thread.

 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(); ;      }  } 

Please go through this chapter and more from this book to get a clear picture about threading:

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

like image 88
Igoy Avatar answered Sep 28 '22 08:09

Igoy