12

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.

Dogu Arslan
  • 3,292
  • 24
  • 43
  • Any sources on using `ConfigureAwait(false)` for server-side code? As I remember, it's quite the opposite. – kamil-mrzyglod Apr 05 '19 at 20:19
  • referring here: https://msdn.microsoft.com/en-us/magazine/jj991977.aspx the recommendation is use it when you can the exception is for methods that require actual context. Nevertheles the question is specific to azure functions. – Dogu Arslan Apr 05 '19 at 20:24

1 Answers1

18

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.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • 4
    In addition don't use `ConfigureAwait` with [DurableFunctions](https://learn.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-overview) when awaiting `ActivityFunctions` in the orchestrator function. See [https://github.com/MicrosoftDocs/azure-docs/issues/24080](https://github.com/MicrosoftDocs/azure-docs/issues/24080). – Marc Apr 09 '19 at 08:44
  • this was very helpful. what do you mean by "The v1 host would strip out the SynchronizationContext"? – gabe Aug 17 '19 at 00:02
  • 1
    @gabe: The v1 host was an ASP.NET WebAPI process (at least for HTTP-triggered functions). But before it called into your function code, it would deliberately remove the ASP.NET `SynchronizationContext`. – Stephen Cleary Aug 17 '19 at 13:31