palm snow
palm snow

Reputation: 2392

thread context for custom event?

I have some code like this

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

My question is that when OnSomeEvent is fired and this method Foo_SomeEvent is invoked, will it be executed under the context of thread under threadpool or is it thread where i am queing an item on ThreadPool?

Upvotes: 0

Views: 648

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

If it is Foo.MyMethod that triggers the event, since Foo.MyMethod runs on a thread from the pool then the event callback will also run on a thread from the pool. This is easy to verify:

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()
        );
    }
}

prints on my console:

main thread id: 1
Foo_SomeEvent thread id: 3

Upvotes: 3

Related Questions