Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access HttpContext.Current from different threads

I have a C# ASP.NET application which starts about 25 different threads running some methods in a class called SiteCrawler.cs.

In HttpContext.Current.Session I want to save the result of the search made by the user and present it to the user when all the threads are finished running. My problem is that the HttpContext.Current object is null in the spawned threads because it doesn't exist there.

What other options do I have to save user/session specific data without using session because of the limitations when the application is multithreaded?

I have tried to search around every inch of Stackoverflow to find a solution but without any luck....

like image 724
Raydk Avatar asked Jan 19 '12 11:01

Raydk


People also ask

How do I find HttpContext current?

HTTP context accessor. Finally, you can use the IHttpContextAccessor helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.

Is HttpContext thread safe?

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

What is the difference between session and HttpContext current session?

There is no difference. The getter for Page. Session returns the context session.

What is the difference between HttpContext current items and HttpContext current session in asp net?

Item” data is live for single HTTP request/Response where HttpContext. Current. Session data is live throughout user's session.


2 Answers

In my application there are a lot of code that uses HttpContext.Current and I can not modify that code.

worker.DoWork() from sample below uses that code. And I had to run it in separate thread.

I came to the following solution:

 HttpContext ctx = HttpContext.Current;  Thread t = new Thread(new ThreadStart(() =>                 {                     HttpContext.Current = ctx;                     worker.DoWork();                 }));  t.Start();  // [... do other job ...]  t.Join(); 
like image 128
Dmitry Andrievsky Avatar answered Oct 09 '22 15:10

Dmitry Andrievsky


Have a look at this article by Fritz Onion: Use Threads and Build Asynchronous Handlers in Your Server-Side Web Code. It's quite long, but your requirement is not too trivial.

Also K. Scott Allen posted a somewhat shorter article about this very issue: Working With HttpContext.Current

like image 25
Dennis Traub Avatar answered Oct 09 '22 15:10

Dennis Traub