简体   繁体   English

这对静态类很好用吗?

[英]Is this a good use for a static class?

I have a read only list that is shared across all instances of the application and won't change very often. 我有一个只读列表,在应用程序的所有实例之间共享,并且不会经常更改。 Is it good practice to make a property on a static class to access this list? 在静态类上创建属性以访问此列表是一种好习惯吗? the list is filled from the database in the static constructor. 列表从静态构造函数中的数据库填充。 Setting the app pool to recycle every night would guarantee the list would be up to date every day correct? 将应用程序池设置为每晚重新循环可以保证列表每天都是最新的正确吗? Are there any reasons this is a bad idea? 有什么理由这是个坏主意吗? Thanks! 谢谢!

This looks like a good solution. 这看起来是个很好的解决方案。 You may want to use a sealed class instead, to avoid sub-classes messing with it. 您可能希望使用密封类,以避免子类弄乱它。

The issue with global state is when it is being changed by the application. 全局状态的问题在于应用程序正在更改它。 In this case, that's not a problem. 在这种情况下,这不是问题。

Nothing wrong with a static class. 静态类没有错。 You could also use the cache, which would work in a similar way. 您也可以使用缓存,它可以以类似的方式工作。 The cache gives you the added bonus of being able to invalidate the cache on a timed basis of your choosing. 缓存为您提供额外的好处,即能够在您选择的时间基础上使缓存无效。

You should understand how static properties are stored. 您应该了解静态属性的存储方式。

Roughly, all static state is placed in the instance of RuntimeType (which, in turn, is created when static ctor is called). 粗略地说,所有静态都放在RuntimeType的实例中(反过来,它是在调用静态ctor时创建的)。 CLR via C# describes this mechanism in details. CLR通过C#详细描述了这种机制。

In the light of that, this collection will be shared across all instances, but you should keep in mind all potential memory leaks (just imagine the situation when you're subscribing on the collection events and all pages became reachable even when they're closed etc.) 鉴于此,此集合将在所有实例中共享,但您应该记住所有可能的内存泄漏(想象一下当您订阅集合事件时所有页面即使在它们关闭时也可以访问等等。)

The second disadvantage of this approach is that this collection is not up-to-date. 这种方法的第二个缺点是这个集合不是最新的。 The third disadvantage is that you need to take care about thread safety of this collection, which, in turn, will harm your performance. 第三个缺点是你需要注意这个系列的线程安全性,这反过来会损害你的性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM