Reputation: 173
Using a C#, WPF, MVVM, Prism, MEF. I need the external effects (I have it from the View is called Dispose ()) to free resources in the ViewModel, used in the View. I use something like the following code:
public class MyViewModel: IDisposable, IMyViewModel, ...
{
private bool disposed = false;
private System.Timers.Timer timer;
public MyViewModel()
{
timer = new System.Timers.Timer();
timer.Interval = 100;
//timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if(!this.disposed)
{
if(disposing)
{
// Dispose managed resources.
timer.Dispose();
timer = null;
//GC.KeepAlive(timer);
//GC.Collect();
}
disposed = true;
}
}
~MyViewModel()
{
Dispose(false);
}
}
As such, the View and ViewModel instances are not destroyed and there is a memory leak. If you delete the interface and its methods IDisposable, the View and ViewModel deleted successfully.
I using ANTS Memory Profiler. On next diagram you can see three instance, from DisposableReflecationComposablePart, but must be a one instance.
I can not understand what was happening. Any ideas?
Edit: I understand that my statements explain the problem is the link: http://mef.codeplex.com/wikipage?title=Parts%20Lifetime&referringTitle=Guide
in the following sentence: Thus, the container will not hold references to parts it creates unless one of the following is true:
The part is marked as Shared
The part implements IDisposable
One or more imports is configured to allow recomposition
Upvotes: 2
Views: 3809
Reputation: 25211
See my question here for answers that may help you.
I was in a similar situation and ended up using a custom interface, let's say ICleanup
, instead of IDisposable
in order to avoid having MEF keeping a reference to my views.
I consider this to be a very big flaw in MEF's design. I thought they would at least let each part decide for itself whether a reference to it should be kept by using a certain attribute or by implementing an interface...
Upvotes: 3