Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 238
Michael Mankus Avatar asked Dec 01 '25 16:12

Michael Mankus


2 Answers

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).

like image 123
SomeWritesReserved Avatar answered Dec 03 '25 05:12

SomeWritesReserved


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.

like image 26
Daniel Hilgarth Avatar answered Dec 03 '25 06:12

Daniel Hilgarth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!