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)

{
// 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);




Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: