静电一次性物品 [英] Static disposable objects

查看:91
本文介绍了静电一次性物品的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  • 我应该如何管理带有一次性物品的 static 类?有没有经验法则?

  • How should I manage static classes with disposable items? Are there any rules of thumb?

基本上,我应该重构并制作以下​​ DisposableDataManager non-
静态
还是将所有内容留给 GC 很好吗?

Basically, should I refactor and make the following DisposableDataManager class non- static or is it fine to leave everything to GC?

public static class DisposableDataManager
{
    // ImageList is an 'IDisposable'.
    public static ImageList FirstImageList { get; private set; }
    public static ImageList SecondImageList { get; private set; }

    static DisposableDataManager()
    {
        FirstImageList = CreateFirstImageList();
        SecondImageList = CreateSecondImageList();        
    }

    // ...
}


推荐答案

这实际上取决于资源的配置对您来说有多重要。当您的应用程序关闭时,无论如何打开的所有句柄(文件,网络连接,图形等)都将被释放,因此 没问题。如果您希望处置以便有条不紊地发布,那就更成问题了,例如在关闭流之前冲洗流。 CLR竭尽全力在进程退出之前运行终结器,这在某些情况下将依次调用 Dispose -但这不是问题。我想依靠任何重要的东西。

It really depends on how important it is to you that the resources are disposed. When your application closes, all handles it had open (files, network connections, graphics etc) will be released anyway, so that's not a problem. It's more of a problem if you want disposal for a more orderly release - e.g. flushing a stream before closing it. The CLR makes a "best effort" to run finalizers before the process exits, which will in turn call Dispose in some cases - but that's not something I'd want to rely on for anything important.

因此,对于 ImageList 对象,它确实不应该不会成为问题。您肯定不会泄漏任何资源-操作系统会解决这个问题。

So in the case of ImageList objects, it really shouldn't be an issue. You definitely won't leak any resources - the operating system will take care of that.

话虽如此,我仍然会尝试重构-仅仅是因为全球状态趋于恶化是个坏主意。它使依赖关系隐式化,并使测试更加困难。向构造时需要的每个对象提供相关信息有多困难?

Having said that, I'd still try to refactor - simply because global state tends to be a bad idea. It makes dependencies implicit, and testing harder. How hard would it be to provide the relevant information to each object that needed it at construction time?

(注意:静态变量确实与 AppDomain 而不是整个过程,这使得在 AppDomain s上下移动的应用程序中,整个问题变得更加复杂,但是我怀疑是否与您的情况有关。)

(Note: static variables are really associated with an AppDomain rather than the process as a whole. This makes the whole question more complex in applications where AppDomains are brought up and down, but I doubt that it's relevant to your scenario.)

这篇关于静电一次性物品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆