当事件从任务中被触发时会发生什么?它将具有单独的线程?

时间:2012-09-14 06:39:49

标签: c# .net multithreading event-handling task

当事件从某个任务中被触发时会发生什么?它将具有单独的线程或相同的任务路径?

1 个答案:

答案 0 :(得分:3)

不确定这是否是您所询问的,但事件处理程序将在任务的线程上执行,如此简单测试所示:

class Test
{
    delegate void update();
    static event update updateEvent;

    static void Main(string[] args)
    {
        Console.WriteLine("Parent thread: " + Thread.CurrentThread.ManagedThreadId);
        updateEvent += new update(Test_updateEvent);
        var t = Task.Factory.StartNew(
            () =>
            {
                Console.WriteLine("Task thread: " + Thread.CurrentThread.ManagedThreadId);
                updateEvent();
            });
        t.Wait();
    }

    static void Test_updateEvent()
    {
        Console.WriteLine("Event thread: " + Thread.CurrentThread.ManagedThreadId);
    }
}

输出:

Parent thread: 1
Task thread: 3
Event thread: 3