从任务中激发事件时会发生什么?它会有单独的线程还是相同的任务路径?
不确定这是否是您所询问的,但事件处理程序将在任务的线程上执行,如以下简单测试所示:
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