如何处理同时用于桌面和 Web 的库中的静态变量?
我有一些使用静态变量的 C# 库类。我将这些库类用于桌面和 Web 应用程序。问题是,正如我刚刚发现的,静态变量在 Web 服务器上的表现不太好;这些值在使用该网站的所有会话中共享!
如何保留静态变量的功能以在桌面应用程序中使用,同时确保 Web 服务器上的每个会话都有自己独立的这些变量值 - 但在会话本身内,它的行为仍然像静态变量?
I have some C# library classes that make use of static variables. I use these library classes both for desktop and web applications. Problem is, as I just discovered, static variables don't go down so well on a web server; the values are shared across all sessions using the web site!
How can I preserve the features of a static variable for use in my desktop apps, while making sure that each session on my web server has its own independent values for these variables - but within the session itself, it still really behaves like a static?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
静态变量值在应用程序域中的所有线程之间共享。在 ASP.NET 应用程序中,存储仅与当前用户相关的数据的推荐方法是 会话。
如果您可以修改此共享库的代码,我建议您从这些静态变量中提取一个接口,该接口将提供一种存储值的机制。这将允许每个应用程序提供自己的实现。对于 Windows 应用程序,您可以使用内部使用静态变量的实现。对于 ASP.NET 应用程序,您可以使用 Session。但在所有情况下,您只公开一个接口。这也会产生积极的副作用,使您的代码更容易进行单元测试。
Static variable values are shared across all threads in an application domain. In an ASP.NET application the recommended way to store data that's related only to the current user is the Session.
If you can modify the code of this shared library I would advise you to extract an interface out of these static variables that will provide a mechanism to store values. This will allow each application to provide its own implementation. For a windows application you could use an implementation that internally uses a static variable. For an ASP.NET application you could use the Session. But in all cases you expose only an interface. This will also have the positive side effect of rendering your code easier to unit test.