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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With