自定义事件的线程上下文?

时间:2011-12-14 14:50:04

标签: c# multithreading threadpool

我有一些像这样的代码

MyClass Foo = new MyClass()
Foo.OnSomeEvent += new SomeEvent(Foo_SomeEvent);
ThreadPool.QueueUserWorkItem(Foo.MyMethod, SomeParams);

我的问题是,当OnSomeEvent被触发并且调用了这个方法Foo_SomeEvent时,它是在线程池下的线程的上下文中执行的,还是我在ThreadPool上排队项目的线程?

1 个答案:

答案 0 :(得分:3)

如果是Foo.MyMethod触发事件,由于Foo.MyMethod在池中的线​​程上运行,因此事件回调也将在池中的线​​程上运行。这很容易验证:

public class MyClass
{
    public EventHandler OnSomeEvent;
    public void MyMethod(object state)
    {
        OnSomeEvent(null, null);
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(
            "main thread id: {0}", 
            Thread.CurrentThread.GetHashCode()
        );

        MyClass Foo = new MyClass();
        Foo.OnSomeEvent += new EventHandler(Foo_SomeEvent);
        ThreadPool.QueueUserWorkItem(Foo.MyMethod, null);
        Console.ReadKey();
    }

    static void Foo_SomeEvent(object sender, EventArgs e) 
    {
        Console.WriteLine(
            "Foo_SomeEvent thread id: {0}", 
            Thread.CurrentThread.GetHashCode()
        );
    }
}

在我的控制台上打印:

main thread id: 1
Foo_SomeEvent thread id: 3