vendredi 22 novembre 2019

Implementing C# IDisposible

I am trying to work out exactly what I need to do to dispose of a property in C# when using IDisposable. I can see the template, but I am not sure about actually disposing of objects.

I am working with the example given on this site: https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose

I have added 3 properties:

privInt: Private value type. Would I dispose of this as it could be saved on the heap so may require GC??? If I would then how, cannot set to null or call dispose? If not then I assume it has to be left to GC - but is it not the point of Dispose to free resources???

NonIDisClassInstance - Do I set to null?? Is that enough

Can anyone comment on my implementation below and adivse on what is correct/wrong.

IDisClass - Just call dispose

class BaseClass : IDisposable
{
   // Flag: Has Dispose already been called?
   bool disposed = false;

   // Public implementation of Dispose pattern callable by consumers.
   public void Dispose()
   { 
      Dispose(true);
      GC.SuppressFinalize(this);           
   }

   //Private value type
   private int privInt;

   //Private class that does not implement IDisposible
   Private NonIDisClass NonIDisClassInstance;

   //Private class that does  implement IDisposible
   Private IDisClass IDisClassInstance;

   // Protected implementation of Dispose pattern.
   protected virtual void Dispose(bool disposing)
   {
      if (disposed)
         return; 

      if (disposing) {
         // Free any other managed objects here.
         //
      }

      // Free any unmanaged objects here.     
      DisposeOfThis = ????;
      NonIDisClassInstance = null;
      IDisClassInstance.Dispose();
      disposed = true;
   }

   ~BaseClass()
   {
      Dispose(false);
   }
}

Aucun commentaire:

Enregistrer un commentaire