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 between 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?
Share
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: