【发布时间】:2012-09-14 06:39:49
【问题描述】:
当一个事件被任务触发时会发生什么?它会有单独的线程还是相同的任务路径?
【问题讨论】:
-
一个任务需要通知父对象。该通知是否创建单独的线程?
标签: c# .net multithreading event-handling task
当一个事件被任务触发时会发生什么?它会有单独的线程还是相同的任务路径?
【问题讨论】:
标签: c# .net multithreading event-handling task
不确定这是否是您要问的问题,但事件处理程序将在任务的线程上执行,如以下简单测试所示:
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
【讨论】: