Exchange variables between an asp.net page and the background thread created by the page

I have a multi-year task in my asp.net web application, and therefore I run this task in a new thread and constantly poll to check the status of the thread (using the ticker control that ticks every 5 seconds and returns messages to the server and checks the status flow). I used session state to exchange variables between the stream and the page. But I found out that bad practice is accessing a session from a background thread. What is the best way to exchange variables between a stream and the asp.net page that created this stream?

+2
source share
2 answers

I see no problem using Session - it is basically a thread safe dictionary . You probably need to make sure your background thread blocks SyncRoot ; the page class does this automatically.

There are, of course, other options - static variables (but then you get into AppDomain problems) or out-of-band mechanisms (this is a session), like a database or message service. However, if you have any other need for these technologies, the session is probably the easiest.

A few caveats that I can think of:

  • If a session expires, what happens when you write to it from a background thread? An exception? Saves his life?
  • How do you detect that the background thread is abnormal? Store stream in session?
  • What happens to a session if there is no unhandled exception in the background thread ?
+1
source

This is not a direct answer to your question, but a proposal to use a separate WCF service for lengthy work tasks. Your web server is really busy working on a long task, and I assume that I use a lot of CPU.

Expected Issues

  • Overall web server performance will decrease
  • You cannot scale such a solution

Alternatively, consider including long logic in the WCF service. You can run and check the status of a job by issuing a simple AJAX request with the job ID. Each task can be launched in a separate thread, and the result / status is stored in a reliable storage.

+1
source

All Articles