Sharing variables between an asp.net page and a background thread created by the page
I've a long running task in my asp.net web application and hence I run that task in a new thread and constantly poll to check the status of the thread (by using a ticker control which ticks every 5 seconds and postbacks to the server and checks the status of the thread). I used the Session State to share the variables betw开发者_如何转开发een the thread and the page. But I learned that it is a bad practice to access the session from a background thread. What is the best method to share variables between a thread and the asp.net page which created that thread?
I don't inherently see an issue with using Session - it's basically a thread-safe dictionary. You probably need to ensure that your background thread locks SyncRoot; the Page class does this automatically.
There are, of course, other options as well - static variables (but then you get into AppDomain issues), or out-of-band mechanisms (which is what Session is) like a DB or messaging service. Unless you have some other need for those technologies, though, Session is probably the simplest.
Couple of caveats I can think of:
- If the Session expires, what happens when writing to it from the background thread? Exception? Keeps it alive?
- How do you detect that the background thread has exited abnormally? Store the thread in Session?
- What happens to Session if there's an unhandled exception on the background thread?
It is not a direct answer to your question, rather a suggestion to use a separate WCF service for the long running jobs. Your web server gets really busy working on a long task, which I assume use lots of CPU.
Anticipated problems
- The overall performance of web server will drop
- You will not be able to scale such solution
Alternatively, consider putting the long running logic into a WCF service. You can start and check the job status by issuing simple AJAX query with the ID of the job. Each job can be started in a separate thread and the result/status persisted into a queriable storage.
精彩评论