简体   繁体   中英

Is it correct to assign HttpContext.Current inside a task factory?

I was getting HttpContext.Current as null inside the method which is called inside a task factory. So I assigned the HttpContext.Current to currentContext variable. Then I used the same variable to assign HttpContext.Current.

    var currentContext = HttpContext.Current;
    Task shipmentCreationCompleted = Task.Factory.StartNew(() =>
    {
        HttpContext.Current = currentContext;
        MethodToPerformSomeAction();
    });

It is now working fine without any problem. Please let me know if my code has any problem technically. Or is there any alternate way to handle this problem?

Finally i used like this based on the comment,

Task shipmentCreationCompleted = Task.Factory.StartNew(currentContext =>
    {
        HttpContext.Current = (HttpContext)currentContext;
        MethodToPerformSomeAction();
    }, HttpContext.Current);

It works great!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM