Is it ever possible in a managed system to leak memory when you make sure that all handles, things that implement IDispose
are disposed?
Would there be cases where some variables are left out?
Is it ever possible in a managed system to leak memory when you make sure that all handles, things that implement IDispose
are disposed?
Would there be cases where some variables are left out?
I don't think C++ style memory leaks are possible. The garbage collector should account for those. It is possible to create a static object that aggregates object references even though the objects are never used again. Something like this:
public static class SomethingFactory
{
private static List<Something> listOfSomethings = new List<Something>();
public static Something CreateSomething()
{
var something = new Something();
listOfSomethings.Add(something);
return something;
}
}
That's an obviously stupid example, but it would be the equivalent of a managed runtime memory leak.
Once all the references to an object are gone, the garbage collector will free that object on it's next pass. I wouldn't say it's impossible to leak memory but it's fairly difficult, in order to leak you'd have to have a reference to an object sitting around without realizing it.
For example if you instantiate objects into a list and then forget to remove them from the list when you're done AND forget to dispose them.
While it is possible that something in the framework has a leak, more then likely you have something that isn't being being disposed of properly or something is blocking the GC from disposing of it, IIS would be a prime candidate for this.
Just remember that not everything in .NET is fully managed code, COM interop, file io like file streams, DB requests, images, etc.
A problem we had a while ago (.net 2.0 on IIS 6) was that we would create an image and then dispose of it but IIS wouldn't release the memory for a while.
It's possible to have leaks if unmanaged resources do not get cleaned properly. Classes which implement IDisposable can leak.
However, regular object references do not require explicit memory management the way lower level languages do.
The only leaks (other than bugs in the runtime which may be present, though not terribly likely due to garbage collection) are going to be for native resources. If you P/Invoke into a native library which opens file handles, or socket connections, or whatever on your managed application's behalf, and you never explicitly close them (and don't handle them in a disposer or destructor/finalizer), you can have memory or resource leaks because the runtime cannot manage all of those automatically for you.
If you stick with purely managed resources, though, you should be just fine. If you experience any form of memory leak without calling into native code, then that's a bug.
As already mentioned the keeping references around will lead to increasing memory usage over time. An easy way to get into this situation is with events. If you had a long living object with some event that your other objects listen to, if the listeners are never removed then the event on the long lived object will keep those other instances alive long after they are no longer needed.
Reflection emit is another potential source of leaks, with e.g. built-in object deserializers and fancy SOAP/XML clients. At least in earlier versions of the framework, generated code in dependent AppDomains was never unloaded...
Delegates can result in unintuitive memory leaks.
Whenever you create a delegate from an instance method, a reference to that instance is stored "in" that delegate.
Additionally, if you combine multiple delegates into a multicast delegate, you have one big blob of references to numerous objects that are kept from being garbage collected as long as that multicast delegate is being used somewhere.
The only reason for memory leak in .NET application is that objects are still being referenced although their life span has ended. Hence, the garbage collector cannot collect them. And they become long lived objects.
I find that it's very easy to cause leak by subscribing to events without unsubscribing it when the object's life ends.
Event Handlers are a very common source of non-obvious memory leaks. If you subscribe to an event on object1 from object2, then do object2.Dispose() and pretend it doesn't exist (and drop out all references from your code), there is an implicit reference in object1's event that will prevent object2 from being garbage collected.
MyType object2 = new MyType();
// ...
object1.SomeEvent += object2.myEventHandler;
// ...
// Should call this
// object1.SomeEvent -= object2.myEventHandler;
object2.Dispose();
This is a common case of a leak - forgetting to easily unsubscribe from events. Of course, if object1 gets collected, object2 will get collected as well, but not until then.
As others have pointed out, as long as there's not an actual bug in the memory manager, classes that don't use unmanaged resources won't leak memory.
What you see in .NET is not memory leaks, but objects that never get disposed. An object won't get disposed as long as the garbage collector can find it on the object graph. So if any living object anywhere has a reference to the object, it won't get disposed.
Event registration is a good way to make this happen. If an object registers for an event, whatever it registered with has a reference to it, and even if you eliminate every other reference to the object, until it unregisters (or the object it registered with becomes unreachable) it will stay alive.
So you have to watch out for objects that register for static events without your knowledge. A nifty feature of the ToolStrip
, for instance, is that if you change your display theme, it will automatically redisplay in the new theme. It accomplishes this nifty feature by registering for the static SystemEvents.UserPreferenceChanged
event. When you change your Windows theme, the event gets raised, and all of the ToolStrip
objects that are listening to the event get notified that there's a new theme.
Okay, so suppose you decide to throw away a ToolStrip
on your form:
private void DiscardMyToolstrip()
{
Controls.Remove("MyToolStrip");
}
You now have a ToolStrip
that will never die. Even though it isn't on your form anymore, every time the user changes themes Windows will dutifully tell the otherwise-nonexistent ToolStrip
about it. Every time the garbage collector runs, it thinks "I can't throw that object away, the UserPreferenceChanged
event is using it."
That's not a memory leak. But it might as well be.
Things like this make a memory profiler invaluable. Run a memory profiler, and you'll say "that's odd, there seem to be ten thousand ToolStrip
objects on the heap, even though there's only one on my form. How did this happen?"
Oh, and in case you're wondering why some people think property setters are evil: to get a ToolStrip
to unregister from the UserPreferenceChanged
event, set its Visible
property to false
.
If you are developing a WinForms application, a subtle "leak" is the Control.AllowDrop
property (used to enable Drag and Drop). If AllowDrop
is set to "true", the CLR will still hold onto your Control though a System.Windows.Forms.DropTarget
. To fix this, make sure your Control
's AllowDrop
property is set to false
when you no longer need it and the CLR will take care of the rest.
It's a myth that you cannot leak memory in managed code. Granted, it's much harder than in unmanaged C++, but there are a million ways to do it. Static objects holding references, unnecessary references, caching, etc. If you are doing things the "right" way, many of your objects will not get garbage collected until much later than necessary, which is sort of a memory leak too in my opinion, in a practical and not theoretical way.
Fortunately, there are tools that can assist you. I use Microsoft's CLR Profiler a lot - it is not the most user friendly tool ever written but it is definitely very useful and it is free.
You may find my new article useful: How to detect and avoid memory and resources leaks in .NET applications
At my last job, we were using a 3rd party .NET SQLite library which leaked like a sieve.
We were doing a lot of rapid data inserts in a weird situation where the database connection had to be opened and closed each time. The 3rd party lib did some of the same connection opening that we were supposed to do manually and didn't document it. It also held the references somewhere we never did find. The result was 2x as many connections being opened as were supposed to be and only 1/2 getting closed. And since the references were held, we had a memory leak.
This is obviously not the same as a classic C/C++ memory leak but for all intents and purposes it was one to us.
The following is also a memory leak which happens in most of the applications.
class MyClass{
private static MyClass _someVar = null;
public MyClass(){
_someVar = this;
}
}
If the intent of this design is not to use the class as a singleton it is a memory leak.
Not really a memory leak, but it is quite easy to run out of memory when using large objects (greater than 64K if I remember correctly). They are stored on the LOH and that ist NOT defragmented. So using those large objects and freeing them frees the memory on the LOH, but that free memory is not used anymore by the .NET runtime for this process. So you can easily run out of space on the LOH by using just a few big objects on the LOH. This issue is known to Microsoft, but as I remember now solution for this is being planned.