I am confused about dispose. I am trying to get my code disposing resources correctly. So I have been setting up my classes as IDisposable
(with a Dispose
method) them making sure that the Dispose
method gets called.
But now FXCop is telling me lots of stuff about disposing = false
and calling Dispose(false)
.
I don't see a Dispose
method that takes a bool. Do I need to make one? If so, why? Why not just have a method that gets called when it is disposing?
I saw some code here: CA1063: Implement IDisposable correctly - Microsoft Docs that shows how to make a Dispose
method that takes a bool
. It says it is for native vs managed resourses. But I thought the whole point of dispose was for unmanaged resourses only.
Also, the line that FXCop is complaining about is this:
~OwnerDrawnPanel()
{
_font.Dispose();
}
It says:
CA1063 : Microsoft.Design : Modify 'OwnerDrawnPanel.~OwnerDrawnPanel()' so that it calls Dispose(false) and then returns.
But Font
does not have a Dispose(bool)
on it (that I can find).
Why do I need a Dispose(bool)
? and if I do, why doesn't Font have it? and since it does not have it, why is FXCop asking me to use it?
Thanks for all the great answers. I think I understand now. Here is
Disposing of "unmanaged" resources falls into two categories:
Bitmap
, Font
etc), but still need Dispose
to be called to clean them up properly.Dispose(bool)
is used to tell the difference between the two:
Dispose
is directly called on your object, you want to free both kinds of "unmanaged" resources.Dispose(bool)
is a pattern to implement Finalize
and Dispose
to Clean Up Unmanaged Resources , see this for detail