简体   繁体   中英

MVVM-WPF: Dynamic view and memory leak?

I have a long-lived ViewModel and a dynamic View that is added to the visual tree whenever the user wants to see the ViewModel. When the user closes the View, it is removed from the visual tree. I intentionally put 50mb of dummy data in the View(UserControl):

private byte[] data = new byte[50 * 1024 * 1024];

I watched the Process Explorer memory shoots up when I add the View onto the visual tree. I closed the View(unloading it from the visual tree) and then explicitly called the Garbage collect method:

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

However, the memory didn't reduced and whenever i add the View onto the visual tree, another 50mb is added. I am sure my ViewModel is not referencing the View.

Any suggestions to solve this problem or explain to me why this is so?

Thanks!

EDIT:

I used the dotTrace memory profiler and found that there is no reference from the ViewModel. All references to the "data" variable are UI objects. Most of it are from template. How should I correctly solve this issue?

Try this tool it helped me a lot. http://www.jetbrains.com/profiler/ (there is a 10 day trial)

Not implementing INotifyPropertyChanged on classes that are bound to in the UI can cause a memory leak. See: http://support.microsoft.com/kb/938416/en-us

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM