Reputation: 11963
I know its always a good practice to wrap every single IDisposible
objects with using
. But is it possible to create permanent memory leak like c++ if I failed to do so? (by permanent I mean the life time of the application)
I know GC will have a hard time with COM and native resources but lets assume I am using managed code only. No COM, no unsafe only built in packages and managed code. Is there any IDisposible
that GC won't be able to collect even after the variable is out of scope?
Upvotes: 1
Views: 365
Reputation: 13535
Yes it is possible. A common source of issues are Timers which when not disposed will keep a reference to your callback and keep your class which implements the callback and all associated data alive forever.
Besides unmanged objects another very common source are event registrations which are unregistered in the dispose method if no weak event pattern is used. That can become pretty cumbersome to manage which is the reason why WPF relies entirely on weak events to work around the lifetime issue. WPF Windows have no Dispose method. Lifetime is managed by the garbage collector entirely.
If you are working with WinForms on the other hand you will quickly notice what happens with if you forgot to call Dispose on some windows ...
Upvotes: 0
Reputation: 6981
Yes. When the GC collects an object, then the object's finalizer is run. In most implementations of IDisposable
, IDisposable.Dispose()
is called from the finalizer, which means that the object will be disposed when it is garbage collected.
However, sometimes this is not the case. For example, many objects in the SharpDX library are not disposed in their finalizers, so if you do not dispose them, then the native objects that they represent (in this case, graphics resources) will not be cleaned up and you will end up with a memory leak. This is actually the source of this problem I had a while ago.
Edit: I didn't see that you mentioned no unmanaged resources. In that case, no. All C# code that doesn't depend on unmanaged code must depend on the BCL, which does not easily create memory leaks.
Upvotes: 2