简体   繁体   中英

What is the best way to handle cross-thread events in C#

I'm trying to develop a way to fire events from a thread and handle then on the main UI thread. In the event handlers I will be updating the UI, and I would rather not have to check for InvokeRequired everywhere.

I've seen a lot about this from searching, but I've not seen an example anywhere that will work 100% without the possible problems. I've come up with a solution which appears to work, and to the best of my knowledge, addresses the various problems I have read about. I would be keen to hear peoples opinions on this:

public static void SafeInvoke<T>(this EventHandler<T> source, object sender, T args) where T : System.EventArgs
{
    EventHandler<T> handler;

    lock (SyncRoot)
    {
        handler = Volatile.Read(ref source);
    }

    if (handler == null)
    {
        return;
    }

    foreach (Delegate d in handler.GetInvocationList())
    {
        ISynchronizeInvoke target = d.Target as ISynchronizeInvoke;

        if (target == null)
        {
            continue;
        }

        if (target.InvokeRequired)
        {
            target.BeginInvoke(d, new[] { sender, args });
        }
        else
        {
            handler(sender, args);
        }
    }
}

If you are working in .Net 3.5 or higher, you can use Reactive Extensions. It is well suited for this kind of thing.

http://msdn.microsoft.com/en-us/data/gg577609.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM