I am new to the async feature provided in the .NET framework
so in my understanding the benefit provided by the async keyword is that when thread call an async method, it can return in the await point and resume the run properly.
my question is after it return from that point, what is the thread doing ? can it be used to run other task items in Thread pool, if so, there must be still context switches ? if not, why not just spin there ?
===== so there will be other threads to take over the not finished part of the async function, how does this context switch happen, like where are those states stored? and how does another thread take those states
When your code hits an await
expression (assuming the awaitable was not completed synchronously), control returns to the calling method, as if you had written return;
.
(it returns a Task<T>
that the caller can use to await the completion of the async part)
The calling method will then continue execution until it returns (it will usually return immediately as it too await
s the returned task), and so on until it reaches the top of the (user-facing portion of the) call stack.
Once it hits the top of the call stack, that thread will do whatever it naturally does.
If it's a UI thread, it will return to the message loop, keeping the UI responsive.
If it's a ThreadPool thread (or an ASP.Net worker thread), it will return to the pool and wait (synchronously) for more work.
If it's a "raw" thread (the Main thread in a console app, or a new Thread()
, it will terminate.
Task.ContinueWith()
, which takes a callback that captures the current state in something like a closure. See msmvps.com/blogs/jon_skeet/archive/tags/Eduasync/default.aspx - SLaks
Yes, the thread returns and can do other work.
As for why not just spin there
, because it can do other work. There is no point in forcing a thread to remain idle when it has the opportunity to do work.
If you do not care which thread will actually continue doing the work, then you can use Task.ConfigureAwait, like this:
await foo.DoSomethingAsync().ConfigureAwait(continueOnCapturedContext: false);
ConfigureAwait()
has nothing to do with what the thread does next. - SLaks