如何并行在C#中的事件处理程序的执行 [英] How to parallelize event handler execution in C#

查看:225
本文介绍了如何并行在C#中的事件处理程序的执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Kinect的设备和我开发使用C#与它的程序。

I have a Kinect device and I am developing a program with it by using C#.

为了管理设备,我已经使用 AllFramesReady 事件,以便处理的深度和颜色信息。

In order to manage the device, I have used AllFramesReady event in order to process the depth and color information.

我已经创建了一个事件处理程序处理被命名为数据 EventHandler1 。我做了很多处理此事件处理中。

I have created an event handler to process the data which is named EventHandler1. I am doing a lot of processing inside this event handler.

我愿做一个名为第二个事件处理中的一些更多的计算 EventHandler2

I would like to do some more computation inside a second event handler named EventHandler2.

是否有可能在主流程的2个不同的线程运行这2个事件处理它们基本上是平行2功能,?如果可能的话,请你给我一个示例代码这样做?

Is it possible to run this 2 event handlers which are basically 2 functions on parallel, on 2 different threads of the main process? If possible, could you please give me a sample code for doing this?

推荐答案

这是很容易的一类收官;但是,您需要订阅所需的事件之前,聚合所有事件处理成一个单一的事件处理程序。

This is easy enough to wrap up in a class; however, you need to aggregate all the event handlers into a single event handler before subscribing to the desired event.

下面是一个快速和肮脏的类来证明这一点。 。第一个事件,而所有其他人都在默认的线程池执行与该事件调用提供运行内嵌

Here is a quick-and-dirty class to demonstrate this. The first event provided runs inline with the event call while all others are executed on the default thread pool.

class ParallelEvent<TEventArg> where TEventArg : EventArgs
{
    private readonly EventHandler<TEventArg> _handler1;
    private readonly EventHandler<TEventArg>[] _moreHandlers;

    public ParallelEvent(EventHandler<TEventArg> handler1, params EventHandler<TEventArg>[] moreHandlers)
    {
        if (handler1 == null)
            throw new ArgumentNullException("handler1");
        if (moreHandlers == null)
            throw new ArgumentNullException("moreHandlers");
        _handler1 = handler1;
        _moreHandlers = moreHandlers;
    }

    public void Handler(Object sender, TEventArg args)
    {
        IAsyncResult[] asyncResults = new IAsyncResult[_moreHandlers.Length];
        for (int i = 0; i < _moreHandlers.Length; i++)
            asyncResults[i] = _moreHandlers[i].BeginInvoke(sender, args, null, null);

        _handler1(sender, args);

        for (int i = 0; i < _moreHandlers.Length; i++)
            _moreHandlers[i].EndInvoke(asyncResults[i]);
    }
}

现在使用此,我们构建一个ParallelEvent类,它提供其所有的事件处理程序,我们希望在并行运行。然后我们预订与类的处理方法事件测试。最后,我们调用事件'测试',并查看输出。请看下面的例子:

Now to use this we construct a ParallelEvent class providing it all the event handlers we want to run in parallel. Then we subscribe to the event 'test' with the class's Handler method. Finally we call the event 'test' and review the output. Consider the following example:

private static event EventHandler<EventArgs> test;

static void Main()
{
    var e = new ParallelEvent<EventArgs>(Test1, Test2);
    test += e.Handler;
    test(null, EventArgs.Empty);
}

static void Test1(Object sender, EventArgs args)
{
    Console.WriteLine("Start Test 1");
    Thread.Sleep(100);
    Console.WriteLine("End Test 1");
}

static void Test2(Object sender, EventArgs args)
{
    Console.WriteLine("Start Test 2");
    Thread.Sleep(100);
    Console.WriteLine("End Test 2");
}

正如所料上面的程序运行它们并行通过下面的输出演示:

As expected the program above runs them in parallel as demonstrated by the following output:

Start Test 1
Start Test 2
End Test 2
End Test 1

最后你需要对多线程代码了解其他问题。被改变的任何共享状态,现在需要同步等。

Lastly you need to be aware of other concerns regarding multi-threaded code. Any shared state being changed now needs to be synchronized, etc.

随着一点点的工作,你可以适应上面的类暴露的事件,使听众可以订阅和退订将。然后在处理方法,你会通过提取 Delgate.GetInvocationList委托列表()。一旦你有代表的一个列表,您可以处理它们上面一样现有的处理方法。

With a little work you could adapt the above class to expose an event so that listeners can subscribe and unsubscribe at will. Then in the Handler method you would extract the delegate list via Delgate.GetInvocationList(). Once you have a list of delegates you can process them the same as the existing Handler method above.

这篇关于如何并行在C#中的事件处理程序的执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆