一个asp.net页面和页面创建一个后台线程之间共享变量 [英] Sharing variables between an asp.net page and a background thread created by the page
问题描述
我在asp.net web应用程序已经一个长期运行的任务,所以我运行在一个新的线程任务,不断民意测验检查线程的状态(通过使用蜱每5秒回发一个代码控制到服务器并检查线程的状态)。我使用的会话状态共享线程和页面之间的变量。但我了解到,这是一个不好的做法,从后台线程访问会话。什么是共享一个线程,它创建线程asp.net页面之间的变量,最好的方法?
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?
推荐答案
我本来不看使用会话的一个问题 - 它基本上是一个的线程安全的字典。你可能需要确保你的后台线程锁 SyncRoot上; Page类自动执行此操作。
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.
有,当然,其他的选择,以及 - 静态变量(但你进入AppDomain中的问题),或出带外机制(这是会话是什么)如DB或消息服务。除非你有其他需要这些技术,不过,会议可能是最简单的。
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?
这篇关于一个asp.net页面和页面创建一个后台线程之间共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!