Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 663
Anoop H.N Avatar asked Dec 20 '16 06:12

Anoop H.N


People also ask

How does HttpContext current work?

The HttpContext encapsulates all the HTTP-specific information about a single HTTP request. When an HTTP request arrives at the server, the server processes the request and builds an HttpContext object. This object represents the request which your application code can use to create the response.

Is HttpContext thread safe?

HttpContext isn't thread-safe. Reading or writing properties of the HttpContext outside of processing a request can result in a NullReferenceException.

What is HttpContext in. net Core?

HttpContext encapsulates all information about an individual HTTP request and response. An HttpContext instance is initialized when an HTTP request is received. The HttpContext instance is accessible by middleware and app frameworks such as Web API controllers, Razor Pages, SignalR, gRPC, and more.


1 Answers

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!

like image 119
Anoop H.N Avatar answered Sep 22 '22 14:09

Anoop H.N