SynchronizingObject for an event

前端 未结 2 1283
醉话见心
醉话见心 2020-12-06 15:13

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.

相关标签:
2条回答
  • 2020-12-06 15:28

    You may take a look at the BackgroundWorker class.

    0 讨论(0)
  • 2020-12-06 15:42

    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);
            }
        };
    }
    
    0 讨论(0)
提交回复
热议问题