WPF garbage collection for a complex listview - wpf

In perhaps a case of newbie overreach, I'm building a complex control (using WPF C#. see pic) in which automatic garbage collection does not seem to do as well as it could: I can get better memory use if I force a manual gc. I'm not sure if I should worry about it.
The ListView displaying "SectionList" is using a fair bit of memory (perhaps 100MB), as one would expect with all those controls. It's a ListView bound to an ObservableCollection of "sections" (e.g. "Math 125") (typically around 50 or so) a property of a semester object. If I dynamically change the semester to another with similar content (thus binding the listview to a different observable collection of sections) I notice memory usage going up by about 100MB, even after some auto garbage collection. It doesn't seem to be a memory leak, as if I manually force gc I can more or less recover the 100MB.
I've experimented with various virtualization options on the listview e.g. setting IsVirtualizing=true/false, using recycling mode etc. Nothing seems to make much of a difference. There seems to be way more garbage available for pickup than the automatic collector sees and disposes. I know there's garbage there because a manual gc.Collect() collects it. All in all if I force gc from time to time I can keep memory usage of the whole app at around 300MB, but not if I don't.
The question is what might be going on here that the garbage pickup is being missed?
(Or do I completely misunderstand the issues at hand here?)

I can get better memory use if I force a manual gc. I'm not sure if I should worry about it...It doesn't seem to be a memory leak, as if I manually force gc I can more or less recover the 100MB.
If you don't have a memory leak somwhere in your code, you have nothing to worry about really.
This is the nature of nondeterministic garbage collection, i.e. you don't know and you cannot control when the GC returns memory to the operating system. As long as you don't introduce memory leaks that prevent the GC from doing its job propertly, you should be fine.
If memory usage is a hard requirement or if object lifetime may cause side effects in your application, using a managed runtime such as .NET is probably not the best option after all.

Related

How to Release Memory used by Silverlight Controls on closing form

I have a silverlight application in that when a form is opened it is using nearly 17mb but when i close the form it is releasing any memory . i am disposing all the variables and objects but GC is not releasing any thing . i also removed all the controls at runtime when closing form.
when i verified with ANTS Memory profiler . there it is showing as NativeObjectSafeHandle 196440 which is largest one that can be disposed and second largest is UnmanagedMemoryStream .
In memory profiler it is showing lot of silverlight internal references that iam not able to dispose them like styles, system.windows.controls and resources . Even though iam clearing form.resources.clear().
Pls suggest me in releasing the memory .
Thanks
krishna
The best practice is to not force a garbage collection in most cases. Since CLR knows best way to handle it. But if you really wanna force garbage collection try GC.Collect this will force immediate garbage collection of all generations
http://msdn.microsoft.com/en-us/library/xe0c2357(v=vs.110).aspx
Also please refer to the links i provided in comments for better explanation.

WPF performance problem with CommandManager

We've created a new, quite complex, WPF application from the ground up and have run into a performance problem as the number of commands registered with the CommandManager increase. We're using simple lightweight commands in our MVVM implementation, however the third party controls we're using (Infragistics) do not, and call CommandManager.RegisterClassCommandBinding liberally to add RoutedCommands. The performance problem manifests itself as a perceived sluggishness in the UI when responding to user input, for example tabbing between controls is slow, text input is 'jerky' and popup animation is 'clunky'. When the app is first fired up the UI is snappy. As more screens containing Infragistics grids are opened the performance deteriorates.
Internally, the CommandManager has a private field named _requerySuggestedHandlers, which is a List< WeakReference>. I've used reflection to get a reference to this collection, and I've noticed that when I call .Clear(), the responsiveness of the UI improves back to its initial state. Obviously I don't want to go round clearing collections that I know little about, especially using reflection (!) but I did it to see if it would cure the performance problems, and voila it did.
Normally, this situation would clean itself up after a certain amount of time passes. However, the collection of WeakReferences (_requerySuggestedHandlers) will only get trimmed once a garbage collection is initiated, which is non-deterministic. Because of this, when we close down windows containing grids (Infragistics XamDataGrid), the CanExecute property for 'dead' grid commands continue to be evaluated unnecessarily, long after the window is closed. This also means that if we close down a number of windows, the performance is still sluggish until a garbage collect is initiated. I understand that this can happen on allocation, and I've seen that myself because if I open a further window this causes the initial memory (from the disposed Windows) to be collected and performance returns to normal.
So, given the above, here are my questions:
How, and from where, does CommandManager.InvalidateRequerySuggested() get called? I haven't found any documentation on MSDN that explains this in any great detail. I hooked up to the CommandManager.RequerySuggested event and it looks like it's being called whenever controls lose focus.
Is is possible to suppress CommandManager.InvalidateRequerySuggested() being called in response to user input?
Has anyone else run into this issue, and if so, how have you avoided it?
Thanks!
This sounds like one of the rare cases where deterministically calling GC.Collect() is the right thing to do. The ordinary argument against it is that the garbage collector is smarter than you are. But when you're dealing with WeakReference objects, you enter territory where you may know something that the garbage collector doesn't. Kicking off garbage collection is certainly better than clearing _requerySuggestedHandlers - among other things, it won't do anything to the WeakReference objects that point to controls that are still alive.
I'd choose this over trying to figure out how to suppress RequerySuggested, since that would screw up the behavior of those commands that you still care about.

Avoiding disposing system-defined Pen and Brush instances

I understand it is best practise to call Dispose() on instances of Pen and Brush, except if they've been set to the system-predefined values (eg. System.Drawing.Brushes, System.Drawing.Pens or System.Drawing.SystemBrushes)
Trying to dispose a system-defined resource results in an exception being thrown.
It doesn't appear to be obvious how you can detect (apart from wrapping the Dispose() call in a try/catch) whether one of these resources is referencing a system-defined or user-defined value.
This is an old question I know, but I've been doing some research into resource leaks involving GDI objects, and almost every statement in the accepted answer is false. In the interests of accuracy for later readers who find this question via a search, as I did:
There is no requirement to call Dispose.
This statement is misleading. Though technically you can get away with not calling Dispose, it is an extremely poor practice to not dispose of a brush or pen that you own once you're done with it.
The reason is: there is a hard limit (set to ten thousand by default, though that can be increased via registry hacks) of the number of GDI objects that can be outstanding in a process -- not application domain, note -- and the garbage collector might not get around to finalizing resources faster than they are being leaked. Managed memory allocations produce collection pressure but there is no corresponding finalization pressure.
The purpose of garbage collection is to eliminate these kinds of requirements.
It is not. The purpose of garbage collection is to emulate an environment with arbitrarily much memory.
One of the main purposes of IDisposable is to allow a class to clean up unmanaged resources in resource-limited environments.
This is correct.
If you do not call the Dispose() method, the unmanaged resources of the class will be cleaned up once the object is finialized and disposed during garbage collection.
This is sometimes correct; it is correct for GDI objects. It is a good practice for classes which hold on to unmanaged resources to implement finalization semantics as a backstop; an extra layer of protection for people who follow the bad advice given in the accepted answer. You should not rely on finalizers to save you from your mistakes; you should dispose of your resources.
You should only rely on a finalizer to deal with crazy exceptional situations. Consider for example:
Brush myBrush = MakeMeABrush();
DoSomethingWithBrush(myBrush);
myBrush.Dispose();
Suppose a thread abort exception is thrown after the allocation of the brush but before the assignment to myBrush. No combination of try-catch-finally will enable you to clean up that brush via Dispose; you'll have to rely upon the finalizer. That's what the finalizer is for: the completely crazy situations where you cannot dispose yourself. It is not an excuse to be sloppy.
If you "must" call dispose and you do not know if the brush instance is a "system-" or a "normal-" brush then you will have to use a try...catch block.
Though this is again, technically correct, it misses the point completely. If you are in a situation where you do not know whether or not you own the brush then you have a bug in your program design. Do not paper over your bugs with a try-catch block! Fix the bug!
This situation is common to all explicitly-managed resources: the entity which provides the resource and the entity which consumes the resource are responsible for clearly documenting which of the two owns cleaning up the resource. If you don't know whether you own the brush that you've been given or not then someone isn't doing a task they were responsible to do, namely, preventing that situation from ever arising.
If the contract you decide upon is that the entity which provides the resource is responsible for cleaning it up later then your consumer shouldn't be disposing of the brush at all, because that is breaking the contract; the producer will clean that up if it needs to.
If the contract you decide upon is that both the producer and consumer are going to free the resource, then the consumer must call Clone on every brush passed in to ensure that they have a safely disposable resource, and that the producer continues to own a valid resource as well.
If, most likely, the contract you decide upon is that the entity which is consuming the resource is responsible for cleaning it up later then the provider is required to always hand you a brush that you can safely dispose, and is required to not dispose the resource itself. Since the provider knows whether they made the brush themselves or got it from the system, the provider must call Clone() on system brushes to obtain a brush that can be safely disposed, and then pass that to the consumer.
But the contract "no one cleans it up and we hope for the best" is a pretty poor contract.
It is not needed to call Dispose() on SystemBrushes and SystemPens because the GDI+ Library will take care of these resources.
This explanation is an explanation that doesn't actually explain anything. The reason why it is illegal to dispose of one of these brushes is because the lifetime of the brush is equal to the lifetime of the appdomain.
The Remarks section of the class will make note of if there is a requirement to call the Dispose method.
This statement is false. You should make the assumption that it is always necessary to Dispose an IDisposable resource unless you have good reason to believe otherwise. The absence of a line in the documentation is not evidence that disposing is unnecessary.
To end on a positive note:
If I have a graphic-intensive application or class then I will cache instances of the pens and brushes I need. I use them throughout the life of the application or class.
This is a good practice. If the number of brushes and pens created is relatively small and the same ones are being used over and over again, then it makes good sense to cache them permanently. Since their lifetimes are to the end of the program there is no need to dispose them. In this case we are not disposing the garbage because it's not garbage; it's useful. GDI objects that are not cached should of course still be disposed. Again, pursuing a caching strategy is not an excuse to engage in poor practices.
When you are finished with a Graphics object that you create, you must dispose of it by calling its Dispose method. (This rule is true for many different GDI+ objects.) Don't keep it around for a rainy day because it won't be valid later. You must, must, must dispose of it when you are finished with it. If you don't, it could result in image corruption, memory usage issues, or worse yet, international armed conflict. So, please dispose of all Graphics objects properly.
If you create a Graphics object within an event, you really need to dispose of it before exiting that event handler. There is no guarantee that the Graphics object will still be valid in a later event. Besides, it's easy to re-create another Graphics object at any time.
Got from here
http://msdn.microsoft.com/en-us/library/orm-9780596518431-01-18.aspx
First of all, you always should Dispose of brushes when you can and not leave it up to the garbage collector. While GDI will eventually get around to taking care of that stuff (assuming the library gets shut down properly), there's no telling when that may be. In fact, my understanding is that brush handles stick around for the long-term. Over the course of a long-running application, you're looking at a de facto memory leak. Sure, in a small application that won't run for long, or in one that only rarely creates brushes, you can let the system handle it, but that strikes me as sloppy.
As a general rule, whenever I create a brush I do so in a using statement. That automatically calls dispose on the brush without having to worry about it. As an added bonus, since you create the brush inside the statement you know that it's not a predefined brush. Any time you create and use a non-predefined brush, wrap the block in a using and you don't have to worry about it at all. In fact, you don't even need to explicitly call Dispose, since the block will do so even in the case of an exception.
Short answer is,.. if you create it, either delegate responsibility to clean up or clean the objects up yourselves. You can create GDI resource "leaks" by letting things hang in the garbage collector. They may eventually be cleaned up, but they are not doing any good hanging there. i.e. if you don't call "close" or Dispose on opened files, the file's remain locked until the GC "gets around to it"
I could be wrong but I think you can assume that the lifetime (and the disposal) of the predefined brushes and pens is not your app's responsibility and will be handled by the system.
In short: don't call Dispose on the predefined stuff. :)
Only thing come in mind is to have a practice do not use System pens/brushes as parameters to methods.
Just for completeness, using Reflector I see that the System.Drawing.Pen and System.Drawing.SolidBrush classes have a private field named 'immutable'.
This field appears to be set to true when the object refers to a system-defined resource, so you could use reflection to carefully check the value of this field to decide whether to call Dispose() on it.
There is no requirement to call Dispose. The purpose of garbage collection is to eliminate these kinds of requirements.
One of the main purposes of IDisposable is to allow a class to clean up unmanaged resources in resource-limited environments. If you do not call the dispose method, the unmanaged resouces of the class will be cleaned up once the object is finialized and disposed during garbage collection.
If you "must" call dispose and you do not know if the brush instance is a "system-" or a "normal-" brush then you will have to use a try...catch block.
It is not needed to call dispose on SystemBrushes and SystemPens because the GDI+ Library will take care of these resources.
Okay to dispose of SystemFonts and SystemIcons.
The Remarks section of the class will make note of if there is a requirement to call the Dispose method. If the Remarks section recommends to call the Dispose method, then I will do it.
In general, I do not call dispose on pens and brushes. If I have a graphic-intensive application or class then I will cache instances of the pens and brushes I need. I use them throughout the life of the application or class. If I didn't do this then graphics painting performance will suffer trying to create and dispose all those ojects so many times and so frequently. (Hm...now that I think about it, performance is probably why we cannot dispose of SystemBrushes and SystemPens, yet can dispose of SystemFonts and SystemIcons. Even the framework caches SystemBrushes and SystemPens.)

WPF-application memory leak

After certain action (pressing a button that starts a sequence of calculations) in the WPF-application a memory leak occurs (it is visible in the task manager in vm size section) approximately on 10 mbytes after each pressing of the button.
The sequence of calculations does not contain errors.
The use of memory profiler (.NET Memory Profiler) has shown that leaks in .net are not present, but after each pressing of the button the memory size shown in Name/Resource section (marked HeapMemory) increases approximately by 10 mbytes.
I've read posts about leaks in WPF but those are not my case definately.
What can be wrong? Any suggestions? Maybe, someone had the same problem?
Seeing an increase in the used memory is a misnomer in .NET for detecting a memory leak.
It is easy to make a memory leak in WPF, however. I would suggest using a slightly more visual tool like Redgate Ants Memory Profiler (14 day free trial). Use this method to test for leaks:
Press the button once (to eat up any warmup you might have)
Take a snapshot
Press the button again
Take a snapshot
When you go to the "Class List" and check the filter for "From current snapshot show: only new object". This should give you a better picture of whether you have objects that will never be let go.
The other thing about Ants Memory Profiler is that it has links to videos everywhere that instruct you on how to find a leak. Tracking down leaks is a bit of a black art and it's nice to have help.
No, I don't work for Redgate :)
Perhaps you need to use the WeakEvent Pattern as documented on MSDN to avoid leaks?
Listening for events can lead to memory leaks. The typical technique for listening to an event is to use the language-specific syntax that attaches a handler to an event on a source. For instance, in C#, that syntax is: source.SomeEvent += new SomeEventHandler(MyEventHandler).
This technique creates a strong reference from the event source to the event listener. Ordinarily, attaching an event handler for a listener causes the listener to have an object lifetime that influenced by the object lifetime for the source (unless the event handler is explicitly removed). But in certain circumstances you might want the object lifetime of the listener to be controlled only by other factors, such as whether it currently belongs to the visual tree of the application, and not by the lifetime of the source. Whenever the source object lifetime extends beyond the object lifetime of the listener, the normal event pattern leads to a memory leak: the listener is kept alive longer than intended.
(My emphasis.)
I could fix WPF Application memory leak issue by inserting in "thin" places GC.Collect().
Hope this help!

WPF - Dynamic vs Static Resources

I am experiencing an enormous memory leak in my WPF project and am trying to figure out what I can do to minimize it. To access resources I use StaticResource 100% of the time. Should I use DynamicResource where I can? Are there advantages as far as memory management between StaticResource and DynamicResource?
FYI: I have a listbox showing data via a DataTemplate. As the user scrolls up/down memory increases fast, reaching 1GB in just a couple of minutes of scrolling up/down.
This is unlikely to be a StaticResource / DynamicResource thing. Static and dynamic refer to lookup strategies, not retention strategies:
StaticResource means "look up the
resource once, then just keep using
the same value."
DynamicResource means "look up the
resource each time it's needed, in
case the value has changed."
What you are doing therefore sounds correct: use StaticResource for unchanging resources such as DataTemplates (and reserve DynamicResource for resources that may change, such as system brushes that might change if the user changes the system colour scheme). The allocation of the DataTemplate via the StaticResource reference will cost no more memory than allocating it via a DynamicResource reference, and long term will be cheaper because WPF doesn't have to keep going back and re-evaluating the reference.
What is more likely is that your template itself is doing something which, when the template is applied (instantiated on a data item), is allocating memory (or indirectly causing memory to be allocated) in a leaky way. One counterintuitive cause that I've seen for this is if the template uses old-style bitmap effects. Another is if the template invokes code-behind that hooks up event handlers. But neither of these is likely to be affected by the way you reference the template resource.
As far as I know the client's operating system is very important.
WPF is designed to work for Vista and later systems (Windows 7). You may have performance problems with xp users.

Resources