Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

c# - SynchronizingObject for an event

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
        }
    };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...