How do I access HttpContext.Current in Task.Factory.StartNew?

后端 未结 3 1729
鱼传尺愫
鱼传尺愫 2020-12-08 15:23

I want to access HttpContext.Current in my asp.net application within

Task.Factory.Start(() =>{
    //HttpContext.Current is null here
});
相关标签:
3条回答
  • 2020-12-08 16:08

    Task.Factory.Start will fire up a new Thread and because the HttpContext.Context is local to a thread it won't be automaticly copied to the new Thread, so you need to pass it by hand:

    var task = Task.Factory.StartNew(
        state =>
            {
                var context = (HttpContext) state;
                //use context
            },
        HttpContext.Current);
    
    0 讨论(0)
  • 2020-12-08 16:14

    You could use a closure to have it available on the newly created thread:

    var currentContext = HttpContext.Current;
    
    Task.Factory.Start(() => {
        // currentContext is not null here
    });
    

    But keep in mind that a task can outlive the lifetime of the HTTP request and could lead to funny results when accessing the HTTPContext after the request has completed.

    0 讨论(0)
  • 2020-12-08 16:21

    As David pointed out, HttpContext.Current will not work all the time. In my case, about 1 of 20 time, CurrentContext will be null. End up with below.

    string UserName = Context.User.Identity.Name;
    
    System.Threading.Tasks.Task.Factory.StartNew(() =>
    {
        UserName ...
    }
    
    0 讨论(0)
提交回复
热议问题