How to use non-thread-safe async/await APIs and patterns with ASP.NET Web API?

Entity Framework will (should) handle thread jumps across await points just fine; if it doesn’t, then that’s a bug in EF. OTOH, OperationContextScope is based on TLS and is not await-safe.

1. Synchronous APIs maintain your ASP.NET context; this includes things such as user identity and culture that are often important during processing. Also, a number of ASP.NET APIs assume they are running on an actual ASP.NET context (I don’t mean just using HttpContext.Current; I mean actually assuming that SynchronizationContext.Current is an instance of AspNetSynchronizationContext).

2-3. I have used my own single-threaded context nested directly within the ASP.NET context, in attempts to get async MVC child actions working without having to duplicate code. However, not only do you lose the scalability benefits (for that part of the request, at least), you also run into the ASP.NET APIs assuming that they’re running on an ASP.NET context.

So, I have never used this approach in production. I just end up using the synchronous APIs when necessary.

Leave a Comment