Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ThreadStatic in asynchronous ASP.NET Web API

Is there a possibility to use thread static like variables within a single request? The current code uses a thread static variable for logging purposes and now we want to use async controller methods (with async and await pattern) which results in problems because the variable is null when a new thread is opened.

like image 773
Nico Avatar asked Feb 28 '17 11:02

Nico


People also ask

Is ASP Net Web API asynchronous?

Thanks to support for asynchronous programming in . NET 4.5 and C# 5, it is extremely easy to write asynchronous methods for an ASP.NET Web API service. Simply set the return type either to Task (if the synchronous version returns void) or to Task<T>, replacing T with the return type of the synchronous method.

What is asynchronous in Web API?

An asynchronous method allows you to start a long-running operation, returns your thread to the pool, and wakes up on a different thread or the same depending on the availability of threads in the pool at that time. Now create an application.

Can we use async await in Web API?

The async/await feature solves three performance or scalability problems: They can make your application handle more users. If you have requests that access an external resource such as a database or a web API then async frees up the thread while it is waiting.

How use async await in asp net?

You can use the await keyword only in methods annotated with the async keyword. The await keyword does not block the thread until the task is complete. It signs up the rest of the method as a callback on the task, and immediately returns.


1 Answers

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

To work around this, you can either use AsyncLocal<T> (available in .NET 4.6), or (if you must) HttpContext.Current.Items. Of those two, I would definitely recommend AsyncLocal<T> over Items, if it's available on your platform.

like image 159
Stephen Cleary Avatar answered Sep 20 '22 21:09

Stephen Cleary