What does the thread do after returning from the async point?

I am new to the asynchronous function introduced in the .NET framework

therefore, in my understanding, the advantage provided by the async keyword is that when a thread calls the async method, it can return to the expected point and resume execution.

my question is after it returns from this point, what does the thread do? can it be used to start other task elements in the thread pool, if so, should there still be context switches? if not, why not just spin there?

===== so there will be other threads to capture the incomplete part of the asynchronous function, how does this context switch happen, for example, where are these states stored? and how another thread accepts these states

+4
source share
2 answers

When your code falls into an await expression (assuming that the expected was not executed synchronously), control returns to the calling method, as if you had written return; .
(it returns a Task<T> that the caller can use to wait for the async part to complete)

Then the calling method will continue to execute until it returns (it usually returns immediately, like it, await returned task) and so on until it reaches the top (stack).

As soon as it hits the top of the call stack, this thread will do what it naturally does.

If it is a user interface thread, it will return to the message loop, preserving the user interface.

If it is a ThreadPool thread (or an ASP.Net workflow), it will return to the pool and wait (synchronously) for more work.

If it is a raw thread (main thread in a console application or new Thread() , it will be terminated.

+5
source

Yes, the thread is returning and may do other work.

As for why not just spin there , because it can do other work. It makes no sense to keep a thread idle when it has the ability to do work.

If you don't care which thread really continues to do the job, you can use Task.ConfigureAwait, for example:

 await foo.DoSomethingAsync().ConfigureAwait(continueOnCapturedContext: false); 
+1
source

Source: https://habr.com/ru/post/1498294/


All Articles