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....
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.
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.
There is no difference. The getter for Page. Session returns the context session.
Item” data is live for single HTTP request/Response where HttpContext. Current. Session data is live throughout user's session.
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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With