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.
public delegate void UpdateMeLabel(string _str, Color _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.
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;
}
}
6 comments:
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
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!! :)))))
This has to be one of the simplest, most elegant explanations I've seen on thread-safe delegates. Thank you!
Thanx!
No better, simpler explanation. The less one explain the better it is for newbies. You proved it. Thanksss..
thx man this one is the most clear solution worked for me.
Post a Comment