我应该在单例上实现IDisposable吗? [英] Should I implement IDisposable on a singleton?

查看:86
本文介绍了我应该在单例上实现IDisposable吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Windows服务,其中包含一个单例,该单例又使用一些记录器,消息队列侦听器等.这些类实现IDisposable.我应该在单例本身中实现IDisposable还是做其他事情以确保服务停止/崩溃后,使用本机资源一切正常? 单例是这样实现的:

I have a windows service, which contains a singleton which in turn uses some loggers, message queue listeners and so on. Those classes implements IDisposable. Should I implement IDisposable in singleton itself or do something else to ensure that after service stop/crashing everything will be okay with native resources? The singleton is implemented like this:

public class Temp
{
   private static readonly Lazy<Temp> instance = new Lazy<Temp>(() => new Temp());

   private Temp()
   {
      // create IDisposable objects which use native resources
   }

   public static Temp Instance
   {
      get
      {
         return instance.Value;
      }
   }
} 

推荐答案

我宁愿不实施 IDisposable在单例上:IDisposable 激发开发人员以处置(单个)实例:

I'd rather not implement IDisposable on singleton: IDisposable provokes developer to Dispose the (single) instance:

  using(var temp = Temp.Instance) {
    ...
  }

导致在应用程序的其他部分中发生(可能)崩溃(因为已丢弃单个Temp实例):

which leads to (possible) crash in some other part of the application (since the single Temp instance has been disposed):

  Temp.Instance.SomeFucntion(); // <- possible fail, since Temp.Instanceis disposed

在极少数情况下,如果您必须发布所需的某些资源,我会使用ProcessExit 事件

In some rare case if you have to release some resouces aquired, I'd use ProcessExit event

public class Temp {
   private static readonly Lazy<Temp> instance = new Lazy<Temp>(() => new Temp());

   private void OnProcessExit(Object sender, EventArgs e) {
     // Release native resource if required:
     // some resources e.g. files will be closed automatically,
     // but some e.g. transactions should be closed (commit/rollback) manually
     try {  
       ...
     }
     finally { 
       AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
     }   
   }

   private Temp() {
     // create IDisposable objects which use native resources

     // If you have to release some resouces on exit
     AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
   }

   public static Temp Instance {
     get {
       return instance.Value;
     }
   }
} 

这篇关于我应该在单例上实现IDisposable吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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