25 November 2008

C# Illegal Cross Thread Operation Problem Solution

In Visual Studio, using .NET Framework,
if you are trying to access a user interface control, in multi thread operation, you may get this error Illegal Cross Thread Operation .

That is the thread other than the thread it was created on has no access to change the control interface properties.
To avoid the Illegal Cross Thread Operation error here is the solution;
  • Make a delegate for the control which you want update in multi threading.
  • Check if needs InvokeRequired.
  • Invoke the control, then it will invoke ones again, by its creator object.
  • Second time the control invokes, set its properties as you wish.
The Following C# sample code shows all these steps.
public delegate void UpdateMeLabel(string _str, Color _fontcolor);
public void FormTxtUpdate(string str, Color fontcolor)
{
if (this.label1.InvokeRequired)
{
UpdateMeLabel updaterdelegate = new UpdateMeLabel(FormTxtUpdate);
this.Invoke(updaterdelegate , new object[] { str, fontcolor });
}
else
{
label1.Text = str;
label1.ForeColor = fontcolor;
}

}
By this way, we update the control label1, its text and color values. For example call FormTxtUpdate("Hello World", Color.Red) in multi thread operation, Then label1 text will set to "Hello World" and its color set to Red.

6 comments:

Navin C said...

Hey Dear,
Great answer. Many many thanks for such a nice cute..very-very sweet answer :) Keep it up dear


Thanks lots again!

Navin C.
navin2k6@gmail.com

anlazarov said...

You are the best - I spent all day looking for a solution, and writing hundreds of rows of code, and you helped me just at the end of the work day!!! SOOOO NICE!! :)))))

Jon W said...

This has to be one of the simplest, most elegant explanations I've seen on thread-safe delegates. Thank you!

Anonymous said...

Thanx!

nawfal said...

No better, simpler explanation. The less one explain the better it is for newbies. You proved it. Thanksss..

armut said...

thx man this one is the most clear solution worked for me.