ThreadStatic in ASP.NET Asynchronous Web Interface

Is it possible to use streaming static variables in a single request? The current code uses a static thread variable for logging purposes, and now we want to use the async controller methods (with the async and await pattern), which leads to problems because the variable is null when opening a new thread.

+1
asp.net-web-api async-await threadstatic
source share
1 answer

await can cause thread transitions, so static thread variables will naturally cause problems.

To get around this, you can use AsyncLocal<T> (available in .NET 4.6) or (if necessary) HttpContext.Current.Items . Of these two, I would definitely recommend AsyncLocal<T> over Items if it is available on your platform.

+6
source share

All Articles