ThreadStatic in asynchronous ASP.NET Web API

跟風遠走 提交于 2019-12-10 16:48:05

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/42507054/threadstatic-in-asynchronous-asp-net-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!