Solving the memory leak issues - wpf

I have read a lot about this topic, and still I don't have the clear path how to proceed. Can anyone point to some resource (or explain) that shows in detailed step how to find the reason why some objects dctor is not called.
basically my logic for testing leak is this (WPF application):
create some View/ViewModel
close the View
call GC.Collect()
After a few seconds a dctor on ViewModel class is normally called, but on my application is never called. I would like to know which object is holding a reference to it at that time, since in my opinion it is the way to find the cause of memory leak.
This classes do not user any unmanaged resources, and do not have IDisposable implemented, which means there is no SupressFinalize call to prevent desctructor execution.
Edit: ViewModel is retrieved through a Static property on ViewModelLocator, and is added List. This is required by TabControl, which needs collection of view models to bind to. View and ViewModel are connected through DataTemplate.

First, search for non-unsubscribed event handlers and static references pointing to your ViewModel, even indirectly. Since you're in a WPF application, also ensure that you don't use DependencyPropertyDescriptor.AddValueChanged which is known to cause leaks by using static references.
If you can't find anything manually, use the awesome (this is my opinion, I'm in no way affiliated with them) SciTech .NET Memory Profiler. You can see for every object all the references it holds and which other objects are holding a reference to it, in a nice graph
view. It also warns you for common memory problems.
EDIT:
ViewModel is retrieved through a Static property on ViewModelLocator
Search no longer, you have your leak. Static references prevent objects from being garbage collected. Remove the static reference or wrap it in a WeakReference.

Related

Clearing memory in WPF?

I'm working on new WPF application. And I'm just wondering do I have to dispose or clear memory in any way in Views or View Models?
I only found information, that I should do it when using com ports or any external devices.
This is a very general question, so it is hard to provide a specific answer. .NET applications are garbage collected, so in general things are cleaned up once you no longer reference them anywhere.
Objects that Need Cleanup
There are certain things that the garbage collector will not clean up for one reason or another. In the vast majority of these cases, the class you are working with will implement the IDisposable interface. The most common things that I run into that are disposable are streams and stream-related classes. However, it is a good idea to check anytime you are using something you are unsure about.
So when it comes to views and view models in WPF, the same rules apply. If you are using something that implements IDisposable, then you need to either call Dispose on it when you are done, or wrap the creation of the object in a using block if it makes sense for the use case.
In some cases, a viewmodel might own an instance of a disposable object. In such a case, the viewmodel should itself implement IDisposable, and ensure it disposes the object within its own Dispose method. You will then need to call Dispose on the viewmodel when you are done with it.
Events
A common source of memory leaks in .NET applications are event handlers. Once an application starts to have some complexity to it, you might find that a temporary object (like some viewmodels) will want to register for events with things that have a longer lifespan (such as a service or persistent utility). Registering an event handler using the += operator creates a hidden reference from the event sending object to the event handling object. You will need to remove these handlers using the -= operator to allow the garbage collector to cleanup the handler and the object that owns it.
If you find yourself in a situation where you do not have a valid place to ensure an event is unregistered, consider using a WeakEventManager to add the handler instead of the += operator. This allows an object to handle events without the event sender having an explicit reference to the handling object. However, there is a very small amount of additional performance and memory overhead registering for events this way, so I would not recommend blindly switching all of your event handlers to weak events. Use it just where you need to.
Keep in mind that there are plenty of cases where not unregistering an event is ok and will not cause any memory leak. This is usually true when both the event sender and the event handler have the same life cycle, as is usually the case with a view and its associated view model. In such a case, it is fine for the view to register for events on the viewmodel and never unregister. As long as both the view and viewmodel stop being referenced by anything, they will get cleaned up regardless of the event that links them together.
Summary
There are no hard rules on whether views and viewmodels need any special handling to clean them up. If they are making use of a feature that requires special cleanup, then you will have to deal with that in whatever way is appropriate.
If you are not using any disposable objects, or other things that need explicit cleanup, then all you have to worry about is removing references to your views and viewmodels when you no longer need them.
If you want more technical information about the garbage collector, take a look at this article. Having an understanding of how it works may help you better understand when and how to clean things up.

Silverlight control not being garbage collected because of command

My control is being kept alive because of command it is bound to. How can I break this reference? This is causing a major memory leak in my application. The control is inside of a DataTemplate so I have no direct access to it.
Here is my ANTS memory profile:
How on earth do I break this connection?
Though I incorporated WeakEventListener, I discovered that my problem was with the control I was using to wrap up my images. I was hooking it up to DownloadProgress, ImageOpened, and ImageFailed events and never unhooked them. My thinking was that nothing else in my code was touching the BitmapImage objects so they would be garbage collected with the control. This, it sees, is not the case. The BitmapImage objects were referenced by a static member (and therefore a GC root) deep within Microsoft's code called "ManagedPeerTable.PeggedManagedPeersWithRefs". It was so deep that a Google search returned only five results for it. Now I suppose there will be six.

Memory Leak with CollectionViewSource.GetDefaultView() in WPF?

I'm wondering what the best practices are for working with CollectionViews in WPF in particular the use of the CollectionViewSource.GetDefaultView() method. Has anyone run into any problems with using GetDefaultView? We're concerned that it may be causing some memory leaks.
Is it generally a better practice to create ListCollectionViews manually rather than rely on GetDefaultView()?
How does WPF manage these views? Do they get GC'd when the collection does? I've seen some articles saying that you need to detach CollectionViews from their source collection otherwise you'll have a memory leak.
Thanks for you help!
Bea states that using CollectionViewSource.GetDefaultView() is her favorite way for accessing the view of a given collection. In addition I have personally never ran into any issues making use of the CollectionViewSource.GetDefaultView() however it is certainly possible in a given scenario.
You have to understand that every collection has a default view and that when you bind a given property to a given collection WPF automatically wraps the collection with a view and binds to the view; not the collection.
Since this is part of the WPF framework you then have to assume that with every collection having a view associated with it that it would then be disposed of when the collection is disposed of. If there is a reference to the collection via a bindable property there is then an associated view referencing the collection whether you make a call to CollectionViewSource.GetDefaultView() or not so you would still be in the same predicament.
Empirical evidence exists that until the collection is out of scope the associated views will not be GC'ed; however keep in mind that this was dealing with a collection with implements INotifyCollectionChanged.
Based on your circumstance a 1:1 relationship between the collection and associated view may exist and therefore the coupling may provide no hindrance whatsoever. In this scenario the view being GC'ed once the collection has gone out of scope is not an issue.
It boils down to treading with caution and making certain that you know what is happening under the covers for the more complex situations so that you can take the appropriate measures.

Automatically calling OnDetaching() for Silverlight Behaviors

I am using several Blend behaviors and triggers on a silverlight control. I am wondering if there is any mechanism for automatically detaching or ensuring that OnDetaching() is called for a behavior or trigger when the control is no longer being used (i.e. removed from the visual tree).
My problem is that there is a managed memory leak with the control because of one of the behaviors. The behavior subscribes to an event on some long-lived object in the OnAttached() override and should be unsubscribing from that event in the OnDetaching() override so that it can become a candidate for garbage collection. However, OnDetaching() never seems to be getting called when I remove the control from the visual tree... the only way I can get it to happen is by explicitly detaching the problematic behaviors BEFORE removing the control and then it is properly garbage collected.
Right now my only solution was to create a public method in the code-behind for the control that can go through and detach any known behaviors that would cause garbage collection problems. It would be up to the client code to know to call this before removing the control from the panel. I don't really like this approach, so I am looking for some automatic way of doing this that I am overlooking or a better suggestion.
public void DetachBehaviors()
{
foreach (var behavior in Interaction.GetBehaviors(this.LayoutRoot))
{
behavior.Detach();
}
//continue detaching all known problematic behaviors on the control....
}
What you really need in this case is not some way to automatically detach but to ensure that the reference held by the long lived object does not keep the behaviour (and therefore everything else it has a reference to) from being garbage collected.
This is acheived by implementing a Mediator pattern. The concept is that you don't give the long-lived object a delegate with a reference to your Behaviour, instead you create a Mediator class as a go-between. The mediator attaches to the long-lived objects event and holds a WeakReference to the behaviour. When the long-lived object fires the event the mediator checks that the WeakReference is still alive, if so calls a method on it to pass on the event. If when the event occurs the mediator finds that the WeakReference is no longer alive it detaches its event handler from the long lived object.
Hence there is nothing stopping the behaviour and everything else involved from being garbage collected all thats left is a very small mediator instance with a dead reference still attached to the long-lived object. Since these mediators are tiny they don't represent a real problem and even those will disappear the next time the event fires.
Fortunately you don't have to build this stuff yourself others have already done it. It is called the WeakEventListener. This blog: Highlighting a "weak" contribution; Enhancements make preventing memory leaks with WeakEventListener even easier! has an excellent set of links on the subject.
Joost van Schaik offers an alternative way to clean up references from attached behaviors, while avoiding the problem with the memory leak. It depends on doing the cleanup work using delegates of the Loaded and Unloaded events of the AssociatedObject.
He also offers a code-snippet for generating stubs for attached behaviors.

What's the best way to avoid memory leaks in WPF PRISM/MVVM application

I have a WPF application based on PRISM that utilizes the MVVM pattern.
I have noticed that occasionally my view models, views and everything connected to them will hang around long after their intended lifespan.
One leak involved subscribing to CollectionChanged on a collection belonging to an injected service, another involved not calling the Stop method on a DispatcherTimer, and yet another required a collection be cleared of it's items.
I feel using a CompositePresentationEvent is probably preferable to subscribing to CollectionChanged, but in the other scenarios I am leaning towards implementing IDisposable and have the views call the Dispose method on the view models.
But then something needs to tell the view when to call Dispose on the view model, which gets even less attractive when the complexity of the views increase, and they start including child views.
What do you think is the best approach to handling view models, to ensure they don't leak memory?
Thanks in advance
Ian
I can tell you that I've experienced 100% of the pain you have experienced. We are memory leak brothers, I think.
Unfortunately the only thing I've figured out to do here is something very similar to what you are thinking.
What we've done is create an attached property that a view can apply to itself to bind a handler to the ViewModel:
<UserControl ...
common:LifecycleManagement.CloseHandler="{Binding CloseAction}">
...
</UserControl>
Then our ViewModel just has a method on it of type Action:
public MyVM : ViewModel
{
public Action CloseAction
{
get { return CloseActionInternal; }
}
private void CloseActionInternal()
{
//TODO: stop timers, cleanup, etc;
}
}
When my close method fires (we have a few ways to do this... it's a TabControl UI with "X" on the tab headers, that kind of thing), I simply check to see if this view has registered itself with the AttachedProperty. If so, I call the method referenced there.
It's a pretty roundabout way of simply checking to see if the DataContext of a View is an IDisposable, but it felt better at the time. The problem with checking the DataContext is you might have sub view models that also need this control. You'd either have to make sure your viewmodels chain forward this dispose call or check all of the views in the graph and see if their datacontexts are IDisposable (ugh).
I sort of feel like there is something missing here. There are a few other frameworks that attempt to mitigate this scenario in other ways. You might take a look at Caliburn. It has a system for handling this where a ViewModel is aware of all sub view models and this enables it to automatically chain things forward. In particular, there is an interface called ISupportCustomShutdown (I think that's what it's called) that helps mitigate this problem.
The best thing I've done, however, is make sure and use good memory leak tools like Redgate Memory Profiler that help you visualize the object graph and find the root object. If you were able to identify that DispatchTimer issue, I imagine you are already doing this.
Edit: I forgot one important thing. There is a potential memory leak caused by one of the event handlers in DelegateCommand. Here's a thread about it on Codeplex that explains it. http://compositewpf.codeplex.com/WorkItem/View.aspx?WorkItemId=4065
The latest version of the Prism (v2.1) has this fixed. (http://www.microsoft.com/downloads/details.aspx?FamilyID=387c7a59-b217-4318-ad1b-cbc2ea453f40&displaylang=en).
My findings so far...
In addition to PRISM, Unity, WPF and MVVM we are also using Entity Framework and the Xceed data grid. Memory profiling was done using dotTrace.
I ended up implementing IDisposable on a base class for my view models with the Dispose(bool) method being declared virtual allowing sub classes the chance to clean up as well.
As each view model in our application gets a child container from Unity we dispose it as well, in our case this ensure that EF's ObjectContext went out of scope. This was our major source of memory leaks.
The view model is disposed within an explicit CloseView(UserControl) method on a base controller class. It looks for an IDisposable on the DataContext of the view and calls Dispose on it.
The Xceed data grid seems to be causing a fair share of the leaks, especially in long running views. Any view that refreshes the data grid's ItemSource by assiging a new collection should call Clear() on the existing collection before assigning the new one.
Be careful with Entity Framework and avoid any long running object contexts. It's very unforgiving when it comes to large collections, even though you have removed the collection if tracking is turned on, it will hold a reference to every item in the collection even though your no longer hanging on to them.
If you don't need to update the entity retrieve it with MergeOption.NoTracking, especially in long lived views that bind to collections.
Avoid views with a long life, don't hold onto them within a region when they are not visibile, this will cause you grief especially if they refresh their data at regular intervals when they are visible.
When using CellContentTemplates on the Xceed Column don't use dynamic resources as the resource will hold a reference to the cell, which in turn keep the entire view alive.
When using CellEditor on the Xceed Column and the resource is stored in an external resource dictionary add x:Shared="False" to the resource containing the CellEditor, once again the resource will hold a reference to the cell, using x:Shared="False" ensures you get a fresh copy each time, with the old one being removed correctly.
Be careful when binding the DelegateCommand to items within the Exceed data grid, if you have a case such as a delete button on the row which binds to a command, be sure to clear the collection containing the ItemsSource before closing the view. If you're refreshing the collection you also need to reinitialize the command as well as the command will hold a reference to each row.

Resources