WCF 服务和单例
我有一个在 IIS 上运行的 WCF 服务。
每次用户登录(使用用户名和密码)时,我都会创建一个 SessionClass,它在线程中每隔几分钟执行一次操作并处理用户请求。
我将在字典中创建的每个新 SessionClass 保存在单个 ServiceClass 中。
如果用户在很长一段时间内(假设 10 小时)没有请求任何内容,则会话应该终止。我终止该线程并从 ServiceClass 单例中的字典中删除 SessionClass。
我的问题是,每次我从字典中删除 SessionClass 时,它都会再次使 ServiceClass 的实例为空,并且下次调用它时,它会再次创建,所以我丢失了我曾经在字典中保存的所有会话。我
尝试在 WCF 服务内部保留对 ServiceClass.GetInstance() 的直接引用(我认为垃圾收集器正在杀死 ServiceClass),但这无济于事......
为什么会发生这种情况?有什么想法吗?
I have a WCF service running on IIS.
Every time a user logs in (with username and password) I create a SessionClass that does something every few minutes in a thread and handle user requests.
I save every new SessionClass that's created in a Dictionary in a singleton ServiceClass.
If a user doesn't request anything for a long period of time (let's say 10 hours) the session should die. I kill the thread and remove the SessionClass from the Dictionary in the ServiceClass singleton.
My problem is that every time I remove a SessionClass from the Dictionary, it makes the instance of the ServiceClass null again and the next time its being called, it's being created again so I lose all the sessions I used to hold in the dictionary...
I tried holding direct reference inside the WCF service to the ServiceClass.GetInstance() (I thought that the garbage collector is killing the ServiceClass) but it won't help...
Why is this happening? Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将您的字典声明为静态字段。
至于为什么目前会发生这种情况,如果没有更多信息就不可能说,请发布一些代码。
更新
根据您的评论,听起来 IIS 正在回收 AppPool 和/或 AppDomain。无论哪种情况,您的 AppDomain 都会被卸载,因此存储在内存中的所有信息都将丢失。
Tess Ferrandez 在这里写了一篇非常好的博客文章,介绍了 IIS 为何这样做
更新2
如果只是数据丢失带来不便,您可以尝试将您的服务托管为托管服务Windows 服务 相反。托管 Windows 服务托管选项启用的方案是在 IIS 外部、非消息激活的安全环境中托管的长期运行的 WCF 服务。服务的生命周期由操作系统控制。但是,如果数据永远不会丢失至关重要,则需要添加持久性机制(数据库、存储在磁盘上的文件中等)并从中读取/写入。
Declare your Dictionary as a static field.
As to why this is currently happening it's impossible to say without more information, please post some code.
Update
Based on your comment it sounds like IIS is recyling the AppPool and / or AppDomain. In either event your AppDomain is unloaded, so all information stored in memory will be lost.
Tess Ferrandez wrote a very good blog post about why IIS does this here
Update 2
If it's merely inconvenient that the data gets lost you may try hosting your service as a managed windows service instead. The scenario enabled by the managed Windows Service hosting option is that of a long-running WCF service hosted outside of IIS in a secure environment that is not message-activated. The lifetime of the service is controlled instead by the operating system. If, however, it is critical that your data is never lost, you'll need to add in a persistence mechanism (database, store in a file on disk etc) and read from / write to there.