Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to guarantee that async method continuation runs on another thread?

Does ConfigureAwait(false) guarantee that continuation runs on a different thread or only signals that it's not compulsory to run on the same thread?

Is there any way to provide that guarantee?

I need to test context flow across threads.

like image 577
Pavel Voronin Avatar asked Dec 04 '14 09:12

Pavel Voronin


People also ask

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.

How does async and await affect execution order?

Execution flow with async and awaitAn async function runs synchronously until the first await keyword. This means that within an async function body, all synchronous code before the first await keyword executes immediately.

What happens when you call async method without await?

The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.

Can async method have multiple awaits?

For more information, I have an async / await intro on my blog. So additionally, if a method with multiple awaits is called by a caller, the responsibility for finishing every statement of that method is with the caller.


1 Answers

Using ConfigureAwait(false) tells the awaiter not to resume on the captured context and so the SynchronizationContext is ignored. That means that the continuation would be scheduled by the default TaskScheduler that uses ThreadPool threads.

If the original thread was a ThreadPool thread, the continuation may run on the same thread, otherwise your guaranteed it's a different thread.

You can start your test using a dedicated thread without a SynchronizationContext (or with ConfigureAwait(false)) to make sure the threads are different before and after the async operation.

like image 139
i3arnon Avatar answered Oct 09 '22 04:10

i3arnon