0

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

4

1 回答 1

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
于 2012-09-14T08:20:28.390 回答