I have a class that spawns another UI thread and does it’s thing. I need to abort that thread and clean up whenever my parent class is destroyed. So how do I know when my parent class is destoryed?
Coming from C++ my first thought was to put this in the destructor. But C# doesn’t really have any destructors – only finalizers and dispose – which from what I understand – may or may not be called (I guess it’s a mood thing for the GC??).
That’s great and simple – if you may or may not want to release your resources.
But where do you put code that ABSOLUTELY POSITIVELY MUST BE EXECUTED whenever an object is destroyed?
You put it in
Dispose(implementing theIDisposableinterface) and then ensure thatDisposeis called when the object is no longer required. There’s a language construct that does just this:foo.Disposewill be called at the end of theusingblock. This is equivalent to:Note that
Disposeis not called automatically when the object leaves scope; you need to do it yourself, using either ausingblock or by calling it explicitly.You should, however, provide a finalizer in
Foothat callsDispose, so that if the object isn’t disposed before the GC gets to it, you aren’t left with unreleased resources:The idea behind the
IDisposablepattern is that it tells you unambiguously when a class needs disposing. Here’s an article that describes how to implement it properly (accounting for possible descendant classes).