I prefer to dispose objects as soon as they are not needed anymore. There are taking up resources, obviously, so in my opinion your best bet would be to initialize and dispose them as close together as possible.
So I vote for your item 3.
As your objects implement the IDisposable
interface, you can easily use the using statement, which even calls the Dispose()
method automatically. It does not get any easier or comfortable than that.
And yes, you will need to unregister the event subscriptions! If you don't, the GarbageCollector
will keep your objects alive, even though they may have already gone out of scope. This would then result in a serious memory leak, as you cannot dispose an out-of-scope object.
If you do not immediately dispose your objects, you are responsible for making sure that their resources will be freed up later. That always means more maintenance overhead. All objects that reference unmanaged resources that are not cleaned up right away after use have to implement their own Dispose()
method. This might result in a longer disposing hierarchy.
Therefore, if you were implementing it like in items 1, 2, 4, and 5 you would still need to make sure that some other class calls Dispose()
on the DC
. And that might prove difficult, as you already said by yourself that you cannot determine when the DC
goes out scope. So do not do that! You're getting into troubles here.
So, again, I vote for item 3. At that point you have full control over the lifetime(s) of your objects and when exactly they are not needed anymore.