Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ConfigureAwait(false) needed/beneficial when awaiting async calls in Azure Functions

It is generally recommended to use ConfigureAwait(false) when awaiting async calls when context is not required. Just wondering is there any benefit of using ConfigureAwait(false) in Azure Functions.

Do Azure Function threads have non-null SynchronizationContext as such it would make beneficial to use ConfigureAwait(false) to avoid unnecessarily capturing it and rescheduling the await continuation back on the captured SynchronizationContext?

It is a bit of a churn to add ConfigureAwait(false) at the end of every async call so prefer to avoid it for the code that runs in Azure Functions if there is no perf/or any other related gain.

Looking at the azure function host code: https://github.com/Azure/azure-functions-host/blob/918b057707acfb842659c9dad3cef0193fae1330/src/WebJobs.Script.WebHost/WebScriptHostManager.cs#L181

it seems like azure function host attempts to strip out the ASP.NET SynchronizationContext before calling the azure function.

like image 792
Dogu Arslan Avatar asked Apr 05 '19 19:04

Dogu Arslan


People also ask

What is ConfigureAwait do in async await?

By default, when you use async/await, it will resume on the original thread that started the request. However, if another long-running process currently has taken over that thread, you will be stuck waiting for it to complete. To avoid this issue, you can use a method called ConfigureAwait with a false parameter.

When should I use the task ConfigureAwait Boolean method?

When an asynchronous method awaits a Task directly, continuation usually occurs in the same thread that created the task, depending on the async context. This behavior can be costly in terms of performance and can result in a deadlock on the UI thread. To avoid these problems, call Task. ConfigureAwait(false) .

What is the purpose of ConfigureAwait ()?

ConfigureAwait(continueOnCapturedContext: false) is used to avoid forcing the callback to be invoked on the original context or scheduler. This has a few benefits: Improving performance.


1 Answers

Just wondering is there any benefit of using ConfigureAwait(false) in Azure Functions.

Not if your code knows it is running in that context, no.

In my Azure Functions code, I divide it up into "library-ish" code in separate library projects, and the "Azure Functions" code. I do use ConfigureAwait(false) in the library projects, since they can (in theory, at least) be reused in other applications.

But for code that knows it is running in Azure Functions, no ConfigureAwait(false) is necessary. The v1 host would strip out the SynchronizationContext, and the v2 host runs on ASP.NET Core which doesn't have a context to begin with.

like image 72
Stephen Cleary Avatar answered Nov 01 '22 06:11

Stephen Cleary