Home
> Uncategorized > How to: Make Thread-Safe Calls to Windows Forms Controls without delegates
How to: Make Thread-Safe Calls to Windows Forms Controls without delegates
If you try to update the UI of a windows form app with a thread spun off by the main thread you get an exception, Microsoft’s suggested solution is as follows;
private void SetText(string text)
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox1.Text = text;
}
}
Which omits the code for the SetTextCallback delegate, which over time, can clutter up your application.
Instead, I would suggest using an Action<T> as follows:
var d = new Action<string>(SetText);
Categories: Uncategorized
Comments (0)
Trackbacks (0)
Leave a comment
Trackback