4

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


2 답변


5

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



1

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
  • @SLaks - I was coming at this from the standpoint of the overall process, not just the one particular thread. I realize that was the OP's original question, but the natural progression of thinking would usually lead to what happens to the rest of the work that needs to be done. - Karl Anderson

Linked


Related

Latest