简体   繁体   English

在C#中处理跨线程事件的最佳方法是什么

[英]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. 我正在尝试开发一种从线程触发事件并在主UI线程上进行处理的方法。 In the event handlers I will be updating the UI, and I would rather not have to check for InvokeRequired everywhere. 在事件处理程序中,我将更新UI,而我宁愿不必到处检查InvokeRequired。

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. 我从搜索中学到了很多,但是在任何地方都没有可能出现问题的100%有效的示例。 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. 如果您使用的是.Net 3.5或更高版本,则可以使用Reactive Extensions。 It is well suited for this kind of thing. 非常适合这种事情。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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