Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to force async/await to continue on the first available thread?

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.

like image 921
Karl Anderson Avatar asked Aug 13 '13 17:08

Karl Anderson


People also ask

Does async await run on separate thread?

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.

Does await stop the main thread?

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.

Why is async await used in the first place?

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.

Do async functions run on another thread?

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.


1 Answers

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.

like image 62
Jon Skeet Avatar answered Nov 09 '22 18:11

Jon Skeet