Why is HttpContext.Current null after await?
今天在对项目代码进行异步化改进的时候,遇到一个奇怪的问题(莫笑,以前没遇过),正如标题一样,HttpContext.Current 在 await 异步执行之后,就会变为 null。
演示代码:
public async Task<IEnumerable<string>> Get()
{
await DoWaitAsync();
DoWork();
return new string[] { "value1", "value2" };
}
private Task DoWaitAsync()
{
return
Task.Factory.StartNew(
() =>
{
// null !!
var httpCtx = System.Web.HttpContext.Current;
Thread.Sleep(1000);
});
}
public void DoWork()
{
//Not null
var httpCtx = System.Web.HttpContext.Current;
}
HttpContext.Current 这个东西,我们并不陌生,在进行 ASP.NET 应用程序开发的时候,我们经常会用到,比如获取当前请求的一些值,首先它是一个线程静态属性(thread-static variable),注意其中的关键字:当前请求和线程,也就是说它是和请求线程相关的,在 ASP.NET 应用程序中,一个请求线程会贯穿整个请求过程,所以我们可以在这个请求的任何地方,都可以访问到 HttpContext.Current,这也就是它的“强大之处”,但是如果涉及到异步多线程呢?就不是这么回事了,因为 HttpContext.Current 依附的是当前请求的主线程,当我们使用 await 异步执行一些代码的时候,再次执行下面的代码,其实就不是当前请求线程了,所以我们再次访问 HttpContext.Current 的时候,就变为 null 了,这个问题告诫我们,ASP.NET 应用程序中,如果进行异步化,使用 HttpContext.Current 一定要小心谨慎。
- 需要注意的是:HttpContext.Current 在没有进行 await 操作的时候,都是可以获取到值的。
如果我们的 ASP.NET 应用程序进行了异步化,然后还必须用到 HttpContext.Current,那我们该怎么解决这个问题?
解决的方式有很多,如果应用程序很简单,我们可以在 await 操作之前,先用变量存储 HttpContext.Current,用到的地方直接用这个变量就行了,当然这不是一个“解决问题”的方法,还有一种是用 Cache,可以参考:system-web-httpcontext-current-nulls-itself-after-checking-for-a-cache,我觉得这种方式也是“瞎忽悠”,没有从根本问题上进行解决。
其实想想问题的根源,就是如何在多个线程中共享一个 HttpContext.Current,这个在 MSDN 中表述为:共享/同步上下文(Synchronization Context)
You can use the TaskScheduler.FromCurrentSynchronizationContext method to specify that a task should be scheduled to run on a particular thread. This is useful in frameworks such as Windows Forms and Windows Presentation Foundation where access to user interface objects is often restricted to code that is running on the same thread on which the UI object was created. For more information, see How to: Schedule Work on a Specified Synchronization Context.
那我们如何在 ASP.NET 应用程序中,进行运用呢?答案很简单,我们只需要在 web.config 中指定 targetFramework 版本为 4.5 即可:
<httpRuntime targetFramework="4.5" />
或者在 appSettings 中添加如下 key(测试可用):
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
参考资料:
- Why HttpContext.Current be null?
- Why is HttpContext.Current null after await?
- Why thread context does not flow to background thread in async/await?
- HttpContext.Current并非无处不在
Why is HttpContext.Current null after await?的更多相关文章
- Why is HttpContext.Current null during the Session_End event?
Why is HttpContext.Current null during the Session_End event? On Session_End there is no communicati ...
- ASP.NET多线程下使用HttpContext.Current为null解决方案 2015-01-22 15:23 349人阅读 评论(0) 收藏
问题一:多线程下获取文件绝对路径 当我们使用HttpContext.Current.Server.MapPath(strPath)获取绝对路径时HttpContext.Current为null,解决办 ...
- ASP.NET多线程下使用HttpContext.Current为null解决方案 2015-01-22 15:23 350人阅读 评论(0) 收藏
问题一:多线程下获取文件绝对路径 当我们使用HttpContext.Current.Server.MapPath(strPath)获取绝对路径时HttpContext.Current为null,解决办 ...
- 多线程中使用HttpContext.Current为null的解决办法
HttpContext.Current.Server.MapPath(logFile) 这个是得到具体路径的方法 正常情况下是可以的 多线程情况下就为null 下边的代码原本的作用是把网站的异常 ...
- HttpContext.Current and Web Api
Using HttpContext.Current in WebApi is dangerous because of async HttpContext.Current gets the curre ...
- HttpContext.Current.Server.MapPath("") 未将对象设置到引用的
在多线程中使用该方法获取目录报错:未将对象设置到引用 #region 上传图片到腾讯 public async Task<Result> UploadImageToWX(string ba ...
- 我所知道的HttpContext.Current
在MVC中,HttpContext.Current是比较常见的对象,可以用它来进行Session,Cache等的保存等.但是它并不是无处不在的,下面就慢慢来揭开它的面纱. 当我们向服务端发送请求的时候 ...
- System.Web.HttpContext.Current.Server.MapPath("~/upload/SH") 未将对象引用设置为实例对象
做项目的时候,System.Web.HttpContext.Current.Server.MapPath("~/upload/SH") 获取路径本来这个方法用的好好的 因为需要 ...
- HttpContext.Current.Server.MapPath("/") 未将对象设置到对象的实例异常。
多线程中的System.Web.HttpContext.Current.Server.MapPath("/") 多线程中Server.MapPath会失效... 网上找到几种解决方 ...
随机推荐
- HDu--我要拿走你的蜡烛
我要拿走你的蜡烛 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Su ...
- ZK 使用jfreeChart
前台: <?page title="Grid使用" contentType="text/html;charset=UTF-8"?> <zk x ...
- (转载)开始iOS 7中自动布局教程(一)
这篇教程的前半部分被翻译出来很久了,我也是通过这个教程学会的IOS自动布局.但是后半部分(即本篇)一直未有翻译,正好最近跳坑翻译,就寻来这篇教程,进行翻译.前半部分已经转载至本博客,后半部分即本篇.学 ...
- 爬虫初探(1)之urllib.request
-----------我是小白------------ urllib.request是python3自带的库(python3.x版本特有),我们用它来请求网页,并获取网页源码. # 导入使用库 imp ...
- HTTP 错误 500.21 - Internal Server Error 处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipelineHandler”
HTTP 错误 500.21 - Internal Server Error 处理程序“PageHandlerFactory-Integrated”在其模块列表中有一个错误模块“ManagedPipe ...
- Repeater的分页
Repeater控件是个好东西.轻量级.又好用.完全的自定义.但是,正是因为这些优点它没有自动分页的功能.这个需要研究一下.我看了一下起点等小说网站,那些什么推荐排名榜用Repeater控件那是很 ...
- java 引入自定义字体font后出现的硬盘吃光的问题
有个需求要用美术字体在图片上写字 用自定义的文字有两个方法: 1. Font dynamicFont = Font.createFont(Font.TRUETYPE_FONT, InputStream ...
- Linux中bashshell的一些知识
数据流重导向 重导向redirect:就是将当前的所得数据输出到其他地方: 三种输出输入的状况,分别是: -标准输入stdin:代码为0:使用<或<< -标准输出stdout:代码为 ...
- .NET的Actor模型:Orleans
Orleans是微软推出的类似Scala Akka的Actor模型,Orleans是一个建立在.NET之上的,设计的目标是为了方便程序员开发需要大规模扩展的云服务, 可用于实现DDD+EventSou ...
- 自己动手模拟开发一个简单的Web服务器
开篇:每当我们将开发好的ASP.NET网站部署到IIS服务器中,在浏览器正常浏览页面时,可曾想过Web服务器是怎么工作的,其原理是什么?“纸上得来终觉浅,绝知此事要躬行”,于是我们自己模拟一个简单的W ...