How do I make event callbacks into my win forms thread safe?

To simplify Simon’s code a bit, you could use the built in generic Action delegate. It saves peppering your code with a bunch of delegate types you don’t really need. Also, in .NET 3.5 they added a params parameter to the Invoke method so you don’t have to define a temporary array.

void SomethingHappened(object sender, EventArgs ea)
{
   if (InvokeRequired)
   {
      Invoke(new Action<object, EventArgs>(SomethingHappened), sender, ea);
      return;
   }

   textBox1.Text = "Something happened";
}

Leave a Comment