Thursday, May 24, 2012

Cross thread operation exception - WinForms C#

InvalidOperationException: "Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on." This is an exception that is raised when we try to access control's(label1) methods from a different thread than the one that created that control.

In a simple scenario, If we try to set a value for a control from another thread using the control's direct property setter, we will receive this exception.

Let us take an example of status label to be updated from another thread, which performs some other operations and wants to update the same on label. This scenario is very common in GUI development using WinForms. We will use InvokeRequired property of the control to find out whether the control can be updated directly using the control's value property.

InvokeRequired is value that indicates whether caller has to "invoke" a method to make any calls on the control. This is because on a different thread. 

Solution: 
step 1:  Declare a delegate to accept a method that sets label's text
step 2:  Write a method that handles both InvokeRequired and direct text setter to update the text of label.
step 3:  When on different thread, that is when InvokeRequired, Invoke the same method by passing it through the delegate and also the text to be updated as parameter

C# code:


private delegate void UpdateText(string text);
private void SeLabelText( string  text)


 {
   if(label1.InvokeRequired)


 {
        label1.Invoke(new  UpdateText (  SeLabelText  ), text); //invoke using a delegate that accepts method and text as param
     } 
   else

 { 
     label1.Text= text;

   }
}


SetLabelText("New label text");

Now call SetLabelText whenever it is required to update the text of label1, no matter what thread you are on and we are ThreadSafe!

No comments:

Post a Comment