I have implemented IDisposable
in a class. The Dispose
method updates rows in a database from in-use to available. I like this non-standard use of IDisposable
because you can use Using
. But...
If I forget to use Using
(or explicitly call Dispose
), the rows stay in use.
Because the GC never calls Dispose
for me, the rows will stay in use forever.
Overriding the Finalize method is useless because, at that point, you can't reliably use the class's managed objects to talk to the database anymore.
Does .NET have something like a "Super IDisposable", where the GC guarantees to call your cleanup method just in case you forgot, BUT where it's still safe to use the class' managed objects?
No, there is no such "Super IDisposable
" interface.
When someone forgets to call Dispose
(presumably, because they forgot to enclose the object in using
) this is a programming error (as opposed to a runtime error). The best you can do in this situation is log as much information as possible to let programmers know what happened, so that they could identify and fix the programming error as soon as possible.
You implement this with a bool
flag that you set to true
inside the Dispose
method, and then check inside the finalizer. If the finalizer runs with the flag being set to false
, you know that there has been no call of Dispose
, so you log an error.