我可以/应该在 asp.net/c# 中使用静态类来共享数据吗?
这是我的情况:我正在构建一个供学校团体使用的在线系统。任何时候只有一所学校可以登录该系统,并且从该学校您将获得大约 13 个用户。然后,他们进入一个教育应用程序,在该应用程序中,他们必须合作完成任务,并且从代码的角度来看,在各处共享变量。
我在想,如果我设置一个具有静态属性的静态类来保存需要共享的变量,这可以使我不必在数据库中存储/访问数据库中的变量,只要静态变量都是在应用程序启动时正确初始化并在结束时清理。当然,我还必须在 get 和 set 方法上加锁,以使变量线程安全。
我内心深处的一些想法告诉我,这可能是一种糟糕的处理方式,但我不确定到底为什么,所以如果人们可以给我他们支持或反对在这种情况下使用静态类的想法,我我们将非常感激。
Here's the situation I have: I'm building an online system to be used by school groups. Only one school can log into the system at any one time, and from that school you'll get about 13 users. They then proceed into a educational application in which they have to co-operate to complete tasks, and from a code point of view, sharing variables all over the place.
I was thinking, if I set up a static class with static properties that hold the variables that are required to be shared, this could save me having to store/access the variables in/from a database, as long as the static variables are all properly initialized when the application starts and cleaned up at the end. Of course I would also have to put locks on the get and set methods to make the variables thread safe.
Something in the back of my mind is telling me this might be a terrible way of going about things, but I'm not sure exactly why, so if people could give me their thoughts for or against using a static class in this situation, I would be quite appreciative.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想在网站上全局共享变量,您应该使用应用程序状态 (System.Web.HttpApplicationState),该状态可在任何名为“Application”的变量的 ASP 页面中使用。
它的工作原理就像会话变量一样,将值存储在哈希表中。唯一的事情是你必须管理锁定才能使其线程安全,但如果我记得很好的话,有内置方法或属性来锁定和解锁变量。
在那里阅读更多内容:
http://msdn.microsoft.com/en -us/library/ms178594(v=VS.100).aspx
If you want to share variables globally on your website you should use the Application State (System.Web.HttpApplicationState) that is available in any asp page with the variable named "Application".
It works just like the Session variable, storing values in a hashtable. The only thing is you'll have to manage locking for it to be thread-safe but if I remember well there are built-in methods or properties to lock and unlock variables.
Read more there :
http://msdn.microsoft.com/en-us/library/ms178594(v=VS.100).aspx