One of the cool things about C# 5.0 is the async/await
keywords and how it simplifies the plumbing you used to have to write with Task Parallel Library (TPL).
My question is if you have thread-agnostic code and you happen to trigger an async operation on the main thread (read: UI thread), but you do not necessarily care if the continuation happens on the main thread, then can you tell the async/await
paradigm that you want it to be continued on the first available thread, even if it is not the main thread?
I would think that being able to do this would greatly increase the efficiency of certain scenarios, but not a silver bullet.
An await expression in an async method doesn't block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method. The async and await keywords don't cause additional threads to be created.
Because await is only valid inside async functions and modules, which themselves are asynchronous and return promises, the await expression never blocks the main thread and only defers execution of code that actually depends on the result, i.e. anything after the await expression.
Note: The purpose of async / await is to simplify the syntax necessary to consume promise-based APIs. The behavior of async / await is similar to combining generators and promises. Async functions always return a promise.
Async programming is about non-blocking execution between functions, and we can apply async with single-threaded or multithreaded programming. So, multithreading is one form of asynchronous programming.
If you don't care where the rest of the method continues, use Task.ConfigureAwait
:
await foo.DoSomethingAsync().ConfigureAwait(continueOnCapturedContext: false);
(You don't have to use a named argument here, but it increases clarity.)
See the "Configure Context" part of Stephen Cleary's "best practices" article for more detail.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With