我应该在单例上实现 IDisposable 吗?

Qué*_*dre 6 .net c# singleton windows-services idisposable

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

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;
      }
   }
} 
Run Code Online (Sandbox Code Playgroud)

Dmi*_*nko 5

我不想在单例上实现 IDisposableIDisposable 激发开发人员处理(单个)实例:

  using(var temp = Temp.Instance) {
    ...
  }
Run Code Online (Sandbox Code Playgroud)

这会导致应用程序的其他部分(可能)崩溃(因为单个实例已被释放):Temp

  Temp.Instance.SomeFucntion(); // <- possible fail, since Temp.Instanceis disposed
Run Code Online (Sandbox Code Playgroud)

在极少数情况下,如果您必须释放获得的一些资源,我会使用ProcessExit 事件

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;
     }
   }
} 
Run Code Online (Sandbox Code Playgroud)


Sri*_*vel 2

不; Singleton 不应该实现IDisposable. 如果有人在其他人需要实例时过早地处置该实例怎么办?

另请注意,IDisposable当您的服务崩溃/停止时,实施不会对您有帮助。您必须手动处理它!但你找不到合适的时间来做这件事。