0

I was testing some async code today and I have something that I don't fully understand.enter image description here

What you are seeing in this photo is the Main thread being released after the DoWorkAsync method. Then the Thread pool assigns us the thread with ID 4 to do some work. In this case, it just Delays. My question is when we are finished with the method that was performed by worker 4 and go back to the main which asynchronously waited why isn't the main thread finishing the work? What does actually happen with this main thread while it was free? Can the thread pool take it in the pool or does it stay somewhere else?

  • I'm not entirely sure exactly what you are asking about, so one of those may answer it: https://stackoverflow.com/q/52686862/11683, https://stackoverflow.com/q/17661428/11683, https://blog.stephencleary.com/2013/11/there-is-no-thread.html. – GSerg Jun 02 '21 at 15:43
  • An Analogy might help. Let's say that I work at sector A. At some random point I need a hammer.I make an async call and I need to wait 2 seconds for the hammer to come.In the mean time I am free to go work somewhere else right?After 2 seconds have passed a Hammer is brought in and you(the other thread) are assigned to paint it and return it to me.Once you return it to me I should continue working in my sector A?But instead you not only paint the hammer but finish the work for me. Thread ID4 is brought back from the method and assigned to line 42 to finish the call instead the main. – Ivailo Manolov Jun 02 '21 at 16:10

1 Answers1

2

With async Task Main, the main thread blocks on the Task returned from the Main method. So Main actually returns but then the main thread blocks on its Task, so the application does not exit until Main completes.

Then the Thread pool assigns us the thread with ID 4 to do some work. In this case, it just Delays.

Not quite. All asynchronous methods begin executing synchronously, so the main thread calls Delay, which sets up a timer and then returns an incomplete task. When the Main method does the await, that causes the Main method to also return an incomplete task. There is no thread pool thread "doing" the delay, since there's nothing to do.

After the await, the Main method continues executing, which is where a thread is necessary again. In a Console app, there's no SynchronizationContext (or TaskScheduler), so the Main method resumes executing on a thread pool thread. This happens after the delay.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810