Should I implement IDisposable on a singleton?

前端 未结 3 867
别那么骄傲
别那么骄傲 2021-01-13 22:19

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. S

3条回答
  •  不思量自难忘°
    2021-01-13 22:52

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

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

    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
    

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

    public class Temp {
       private static readonly Lazy instance = new Lazy(() => 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;
         }
       }
    } 
    

提交回复
热议问题