Please read my previous post Managed Vs Unmanaged Resources and Garbage Collector before satrt reading this one.
As I mentioned dispose pattern is used for explicitly cleaning managed/unmanaged resources. A Dispose method should call the GC.SuppressFinalize method for the object it is disposing. If the object is currently on the finalization queue,GC.SuppressFinalize prevents its Finalize method from being called. Remember that executing a Finalize method is costly to performance. If yourDispose method has already done the work to clean up the object, then it is not necessary for the garbage collector to call the object's Finalizemethod.
As per this pattern, the class needs to impliment the interface IDisposable and the method Dispose() will impliment the clean up code. It should also release all resources owned by its base types by calling its parent type's Dispose method. The below code shows the code structure for the same.
As I mentioned dispose pattern is used for explicitly cleaning managed/unmanaged resources. A Dispose method should call the GC.SuppressFinalize method for the object it is disposing. If the object is currently on the finalization queue,GC.SuppressFinalize prevents its Finalize method from being called. Remember that executing a Finalize method is costly to performance. If yourDispose method has already done the work to clean up the object, then it is not necessary for the garbage collector to call the object's Finalizemethod.
As per this pattern, the class needs to impliment the interface IDisposable and the method Dispose() will impliment the clean up code. It should also release all resources owned by its base types by calling its parent type's Dispose method. The below code shows the code structure for the same.
1: class MyClass : IDisposable { 2: 3: /// <summary>Finalizer that will be called by the GC.</summary> 4: ~MyClass() { 5: Dispose(false); // false == called by the GC => IMPLICITE CALL for unmanaged clean up.. 6: } 7: 8: /// <summary>Immediately releases all resources owned by the object.</summary> 9: public void Dispose() { 10: Dispose(true); // true == called explicitly by user code 11: 12: // We have released our resources already. Tell the GC that it 13: // doesn't need to call the finalizer anymore. 14: GC.SuppressFinalize(this); 15: } 16: 17: /// <summary>Immediately releases all resources owned by the object.</summary> 18: /// <param name="managed">19: /// If true, the object is being disposed explicitly and user wants to remove managed /// resources
20: /// other managed objects it is referencing. If false, other managed objects 21: /// maybe have been destroyed already and destroy only unmanaged. 22: /// </param> 23: protected virtual void Dispose(bool managed) { 24: if(managed) { 25: // Perform finalization of managed objects here 26: } 27: 28: // Perform finalization of unmanaged objects here 29: } 30: 31: }
No comments:
Post a Comment