如何在Task.Factory.StartNew中访问HttpContext.Current?

Tim*_*Tom 20 .net c# asp.net asp.net-4.0 c#-4.0

我想在我的asp.net应用程序中访问HttpContext.Current

Task.Factory.Start(() =>{
    //HttpContext.Current is null here
});
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个错误?

nem*_*esv 35

Task.Factory.Start将启动一个新的Thread,因为它HttpContext.Context是一个线程的本地,它不会被自动复制到新的Thread,所以你需要手动传递它:

var task = Task.Factory.StartNew(
    state =>
        {
            var context = (HttpContext) state;
            //use context
        },
    HttpContext.Current);
Run Code Online (Sandbox Code Playgroud)

  • 是的,值得注意的是,使用对HttpContext.Current的引用可能会在很多时候工作,但不建议这样做,并且有时可能会失败.当http请求完成后,ASP运行时可能会清理对象,然后你会发现像`context.Items [x]`这样的东西不包含你之前放的东西.另见http://stackoverflow.com/questions/8925227/access-httpcontext-current-from-threads (2认同)

小智 8

您可以使用闭包使其在新创建的线程上可用:

var currentContext = HttpContext.Current;

Task.Factory.Start(() => {
    // currentContext is not null here
});
Run Code Online (Sandbox Code Playgroud)

但请记住,任务可以比HTTP请求的生命周期更长,并且在请求完成后访问HTTPContext时可能会导致有趣的结果.