简体   繁体   中英

What thread will these event callbacks occur on?

new System.Threading.Thread(() =>
    {
        var myObject = new CustomObject();
        myObject.SomeEvent += SomeMethod;
    }).Start();

Part 1: Assume I run the above code on my main UI thread in a winforms applications. Which Thread will calls to SomeMethod occur on? Will they occur on the same Thread that was created when I created the object?

Part 2: Using Visual Studio 2010, how can I figure this out on my own? I don't know where you find out what Thread something is running on.

The event handler SomeMethod will run on whatever thread raised the event.

You can set a breakpoint in the event handler SomeMethod and look at the Threads window (you will probably want to give your threads meaningful names to find them).

To find out which thread you are currently executing in, you can use Thread.CurrentThread.ManagedThreadId .

To answer your question: SomeMethod will be executed in the thread that raises the event.

In your case, it actually will never be executed as you assign your method to the event but never actually raise the event.

you may check the ManagedThreadId Property http://msdn.microsoft.com/en-us/library/system.threading.thread.managedthreadid.aspx

@Mike Here is the sample

        Console.WriteLine("Main New Thread : {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);

        new System.Threading.Thread(() =>
        {
            Console.WriteLine("Inside New Thread : {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
        }).Start();

        Console.WriteLine("Main New Thread : {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);

Just wanted to add a simple test that will allow you to check the thread on which the handler executes:

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 = new Thread(
            () =>
            {
                Console.WriteLine("Child thread: " + Thread.CurrentThread.ManagedThreadId);
                updateEvent();
            });
        t.Start();
        t.Join();
    }

    static void Test_updateEvent()
    {
        Console.WriteLine("Event thread: " + Thread.CurrentThread.ManagedThreadId);
    }
}

which prints:

Parent thread: 1
Child thread: 3
Event thread: 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM