Exceptions and memory leaks
This is a theoretical question more than anything else. In the case of C# and .NET, if an .aspx or .ascx script dies due to an unhandled exception, would you normally expect its memory to be released, or is that not a sure thing? In other words, can an unhandled e开发者_高级运维xception itself leak memory?
What is a "memory leak"? In manually managed environments we say that unreferenced allocations are a leak. By this definition, there are no leaks in a GC environment.
However, there are a few scenarios that have the same effect:
Stale References
// create temporary item
Item item = new Item();
// add it to the global map, so Processor::Fetch finds it by ID
itemMap.Add(item.id, item);
Process(item.id);
// remove from cache
itemMap.Remove(item.id);
If Process() throws, the item remains referenced in itemMap
. Unless you regulary throw out the entire map (or you made the wise decision to use weak pointers for the map), the item map will accumulate and hold references to temporaries, blocking memory.
Unmanaged resources
Imagine you have a small managed object that allocates large unmanaged resources, and does not implement IDisposable, or IDisposable isn't used.
These objects might live long enough to get pushed to Gen 2. If there's no other pressure on the managed heap, a Gen 2 collection might never run. You may end up pushing tiny objects into Gen 2 until the unmanaged resources exhaust your memory.
This scenario might sound silly, but that's exactly how COM Interop works (and I have a case ID to prove it).
It's not supposed to, and I've never seen it happen; but it can take a loooong time for the garbage collector to come clean up, sometimes until you've "used" a considerable portion of available memory.
No not usually if all your using is .NET, they only way you can leak memory is if you need to dispose of unmanaged resources.
Some c# objects have a "release" or "dispose" function for this purpose.
精彩评论