如何获取类的多个实例(在不同的线程中)来监听同一个事件?

时间:2013-06-05 18:04:34

标签: c# multithreading events

我是C#中事件处理和线程的新手,所以如果这个问题是基本的话,请原谅我:如何创建几个在不同线程上运行的类,都在监听同一个事件?

例如,我经常以随机的间隔收到一段新数据。当这些数据到达时,我会使用新数据更新一个类,我们称之为MyDataClass,这会引发一个事件:MyDataClass.NewEvent

然后我有一个名为NewEventHandler的班级。触发事件时,此类使用新数据进行一些计算,然后将结果发送到另一个应用程序。

问题是这样的: 我需要有大约30个NewEventHandler个实例都在监听MyDataClass.NewEvent(每个都进行不同的计算并产生不同的结果)。重要的是这些计算全部同时运行 - 一旦事件触发所有30个NewEventHandler实例开始计算。但是,它们是否一起完成并不重要(例如,此处不需要同步)。

如何实际创建NewEventHandler的实例,以便它们在不同的线程上运行,并让它们全部收听MyDataClass.NewEvent的单个实例?

2 个答案:

答案 0 :(得分:2)

在C#中,通常的做法是在触发事件的同一线程上调用事件侦听器的方法。从源类触发事件的标准模板是:

void FireNewEvent() 
{
     var tmp = NewEvent;
     if( tmp != null )
     { 
         tmp(this, YourEventArgsInstance);
     }
}

事件并不多,但是有点荣耀的代表。因此,此调用类似于多播委托调用 - 意味着将在FireNewEvent运行的同一线程上顺序调用所有订阅者。我建议你不要改变这种行为。

如果要同时运行事件订阅者,则在每个订阅者中启动一个新任务。

...
MyDataClass.NewEvent += OneOfSubscriberClassInstance.OnNewEvent;

...
public void OnNewEvent(object sender, YourEventArgs args)
{ 
   Task.Factory.StartNew( () => {

       // all your event handling code here 
   });
}

触发事件的代码将依次触发30个订阅者,但每个订阅者将在TPL调度的自己的线程中运行。因此,委托哪个fires事件将不必等待触发下一个订阅者的处理程序,直到当前被调用的订阅者处理程序处理完该事件为止。

答案 1 :(得分:0)

以下是一个示例/演示,说明如何同步不同的线程并确保它们同时响应事件。您可以将此代码复制并粘贴到控制台应用程序中,以使其运行。

public class Program
{
    private static EventWaitHandle _waitHandle;
    private const int ThreadCount = 20;
    private static int _signalledCount = 0;
    private static int _invokedCount = 0;
    private static int _eventCapturedCount = 0;
    private static CountdownEvent _startCounter;
    private static CountdownEvent _invokeCounter;
    private static CountdownEvent _eventCaptured;


    public static void Main(string[] args)
    {
        _waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
        _startCounter = new CountdownEvent(ThreadCount);
        _invokeCounter = new CountdownEvent(ThreadCount);
        _eventCaptured = new CountdownEvent(ThreadCount);

        //Start multiple threads that block until signalled
        for (int i = 1; i <= ThreadCount; i++)
        {
            var t = new Thread(new ParameterizedThreadStart(ThreadProc));
            t.Start(i);
        }

        //Allow all threads to start
        Thread.Sleep(100);

        _startCounter.Wait();

        Console.WriteLine("Press ENTER to allow waiting threads to proceed.");
        Console.ReadLine();

        //Signal threads to start
        _waitHandle.Set();

        //Wait for all threads to acknowledge start
        _invokeCounter.Wait();

        //Signal threads to proceed
        _waitHandle.Reset();

        Console.WriteLine("All threads ready. Raising event.");

        var me = new object();

        //Raise the event
        MyEvent(me, new EventArgs());

        //Wait for all threads to capture event
        _eventCaptured.Wait();
        Console.WriteLine("{0} of {1} threads responded to event.", _eventCapturedCount, ThreadCount);
        Console.ReadLine();
    }

    public static EventHandler MyEvent;

    public static void ThreadProc(object index)
    {
        //Signal main thread that this thread has started
        _startCounter.Signal();
        Interlocked.Increment(ref _signalledCount);

        //Subscribe to event
        MyEvent += delegate(object sender, EventArgs args) 
        { 
            Console.WriteLine("Thread {0} responded to event.", index);
            _eventCaptured.Signal();
            Interlocked.Increment(ref _eventCapturedCount);
        };

        Console.WriteLine("Thread {0} blocks.", index);

        //Wait for main thread to signal ok to start
        _waitHandle.WaitOne();

        //Signal main thread that this thread has been invoked
        _invokeCounter.Signal();
        Interlocked.Increment(ref _invokedCount);
    }
}