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.