【问题标题】:What will happen when an event gets fired from a task?it will have separate thread?当一个事件被一个任务触发时会发生什么?它会有单独的线程吗?
【发布时间】:2012-09-14 06:39:49
【问题描述】:

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

【问题讨论】:

  • 一个任务需要通知父对象。该通知是否创建单独的线程?

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


【解决方案1】:

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

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

【讨论】:

  • +1,是的 - 触发事件是一种“正常”的基于堆栈的调用/返回机制,并且不能更改线程状态(除非委托函数在自身内部执行线程间信号)。
猜你喜欢
  • 2022-01-06
  • 1970-01-01
  • 2011-01-24
  • 2021-10-01
  • 2017-03-24
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多