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

一笑奈何 提交于 2019-12-11 02:12:02

问题


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?


回答1:


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?



回答2:


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.



来源:https://stackoverflow.com/questions/6152644/sharing-variables-between-an-asp-net-page-and-a-background-thread-created-by-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!