3

With Timer objects, I can set the SynchronizingObject property to avoid having to use invoke when updating the GUI from the timer's event handler. If I have a class that instead subscribes to an event and has to update the GUI in the event handler, is there an analogous concept? Or do I have to write the InvokeRequired boilerplate code?

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
toasteroven
  • 2,700
  • 3
  • 26
  • 35

2 Answers2

3

SynchronizingObject is just an ISynchronizeInvoke property. (That interface is implemented by WinForms controls, for example.)

You can use the same interface yourself, although with a vanilla event there's nowhere to really specify the synchronization object.

What you could do is write a utility method which takes a delegate and an ISynchronizeInvoke, and returns a delegate which makes sure the original delegate is run on the right thread.

For example:

public static EventHandler<T> Wrap<T>(EventHandler<T> original,
    ISynchronizeInvoke synchronizingObject) where T : EventArgs
{
    return (object sender, T args) =>
    {
        if (synchronizingObject.InvokeRequired)
        {
            synchronizingObject.Invoke(original, new object[] { sender, args });
        }
        else
        {
            original(sender, args);
        }
    };
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Is this class appropriate to use when I want to synchronize with a self-defined class (not winforms) as shown here: http://stackoverflow.com/q/10654163/328397 – makerofthings7 May 18 '12 at 16:25
  • @makerofthings7: I don't think it's the approach I'd use in that case, no. If you're using .NET 4, look at what the TPL provides. – Jon Skeet May 18 '12 at 16:27
-1

You may take a look at the BackgroundWorker class.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928