[ACCEPTED]-Implementing IDisposable on a sealed class-pinvoke
The finalizer is necessary as a fallback 5 mechanism to eventually free unmanaged resources 4 if you forgot to call Dispose
.
No, you shouldn't 3 declare a virtual
method in a sealed
class. It wouldn't 2 compile at all. Also, it's not recommended 1 to declare new protected
members in sealed
classes.
A minor addition; in the general case, a common 5 pattern is to have a Dispose(bool disposing)
method, so that you 4 know whether you are in Dispose
(where more things 3 are available) vs the finalizer (where you 2 shouldn't really touch any other connected 1 managed objects).
For example:
public void Dispose() { Dispose(true); }
~MemBlock() { Dispose(false); }
void Dispose(bool disposing) { // would be protected virtual if not sealed
if(disposing) { // only run this logic when Dispose is called
GC.SuppressFinalize(this);
// and anything else that touches managed objects
}
if (ptr != IntPtr.Zero) {
Marshal.FreeHGlobal(ptr);
ptr = IntPtr.Zero;
}
}
From Joe Duffy's Weblog:
For sealed classes, this pattern need not 12 be followed, meaning you should simply 11 implement your Finalizer and Dispose with 10 the simple methods (i.e. ~T() (Finalize) and 9 Dispose() in C#). When choosing the latter 8 route, your code should still adhere to 7 the guidelines below regarding implementation 6 of finalization and dispose logic.
So yes, you 5 should be good.
You do need the finalizer 4 as Mehrdad mentioned. If you want to avoid 3 it, you might take a look at SafeHandle. I don't have 2 enough experience with P/Invoke to suggest 1 the correct usage.
You cannot declare virtual methods in a 11 sealed class. Also declaring protected members 10 in a sealed class gives you a compiler warning. So 9 you've implemented it correctly. Calling 8 GC.SuppressFinalize(this) from within the 7 finalizer is not necessary for obvious reasons 6 but it cannot harm.
Having a finalizer is 5 essential when dealing with unmanaged resources, because 4 they are not freed automatically, you have 3 to do it in the finalizer with is called 2 automatically after the object has been 1 garbage collected.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.