我有一些像这样的代码
MyClass Foo = new MyClass()
Foo.OnSomeEvent += new SomeEvent(Foo_SomeEvent);
ThreadPool.QueueUserWorkItem(Foo.MyMethod, SomeParams);
我的问题是,当OnSomeEvent被触发并且调用了这个方法Foo_SomeEvent时,它是在线程池下的线程的上下文中执行的,还是我在ThreadPool上排队项目的线程?
答案 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