异步ASP.NET Web API中的ThreadStatic [英] ThreadStatic in asynchronous ASP.NET Web API

查看:104
本文介绍了异步ASP.NET Web API中的ThreadStatic的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在单个请求中使用线程静态变量之类的变量?当前代码使用线程静态变量进行记录,现在我们要使用异步控制器方法(具有异步和等待模式),这会导致问题,因为在打开新线程时该变量为null.

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.

推荐答案

await会导致线程跳转,因此线程静态变量自然会引起问题.

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

要解决此问题,您可以使用 AsyncLocal<T> (在.NET 4.6中可用),或(如果需要的话)

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.

这篇关于异步ASP.NET Web API中的ThreadStatic的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆