ThreadStatic in asynchronous ASP.NET Web API
Asked Answered
E

1

5

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.

Ehrenberg answered 28/2, 2017 at 11:6 Comment(0)
M
14

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.

Merlynmermaid answered 28/2, 2017 at 14:14 Comment(2)
Can I ask you the reason why you recommend AsyncLocal over Items?Helico
I recommend AsyncLocal<T> over HttpContext.Current because HttpContext.Current is considered a poor design and has been removed in ASP.NET Core.Merlynmermaid

© 2022 - 2024 — McMap. All rights reserved.