2011-12-14 21 views
0

我有這樣自定義事件的線程上下文?

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

我的問題的一些代碼是,當OnSomeEvent被觸發,該方法Foo_SomeEvent被調用時,將它的線程的上下文中下線程池執行,或者是線程我在哪裏queing的ThreadPool上的項目?

回答

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 
+0

很好的例子舉證它。謝謝 – 2011-12-14 14:58:58