【发布时间】:2012-05-26 14:35:33
【问题描述】:
我想在我的 asp.net 应用程序中访问 HttpContext.Current
Task.Factory.Start(() =>{
//HttpContext.Current is null here
});
我该如何解决这个错误?
【问题讨论】:
标签: c# asp.net .net c#-4.0 asp.net-4.0
我想在我的 asp.net 应用程序中访问 HttpContext.Current
Task.Factory.Start(() =>{
//HttpContext.Current is null here
});
我该如何解决这个错误?
【问题讨论】:
标签: c# asp.net .net c#-4.0 asp.net-4.0
Task.Factory.Start 会启动一个新的Thread,因为HttpContext.Context 是线程本地的,它不会自动复制到新的Thread,所以你需要手动传递:
var task = Task.Factory.StartNew(
state =>
{
var context = (HttpContext) state;
//use context
},
HttpContext.Current);
【讨论】:
context.Items[x] 之类的内容不包含您之前放置的内容。另见stackoverflow.com/questions/8925227/…
您可以使用闭包使其在新创建的线程上可用:
var currentContext = HttpContext.Current;
Task.Factory.Start(() => {
// currentContext is not null here
});
但请记住,任务可能会超过 HTTP 请求的生命周期,并且在请求完成后访问 HTTPContext 时可能会导致有趣的结果。
【讨论】:
正如David 指出的那样,HttpContext.Current 不会一直有效。就我而言,大约 20 次中有 1 次 CurrentContext 将为空。以下面结束。
string UserName = Context.User.Identity.Name;
System.Threading.Tasks.Task.Factory.StartNew(() =>
{
UserName ...
}
【讨论】: