Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent memory leaks in WPF

Working with WinForms you have to free memory after using gdi objects, event handlers, objects from native code, etc.

In WinForms I used to remove for example event handlers in the dispose method.

What is the best workaround to prevent memory leaks in Wpf? Is it the same as in Winforms using Dispose pattern? At all, do I have to care about event handlers, gdi objects in Wpf? What about the runtime created resources(Brushes, etc)?

like image 941
Miklós Balogh Avatar asked Oct 12 '11 08:10

Miklós Balogh


People also ask

How did you avoid memory leaks in C#?

If you have implemented a very long-running or infinite running thread that is not doing anything and it holds on to objects, you can cause a memory leak as these objects will never be collected. The fix for this is to be very careful with long-running threads and not hold on to objects not needed.

How do I reduce memory usage in WPF?

Try this: Open the task manager, go to the processes tab, go to view, select collums and check the box that says VM size. Notice that when you minimize or restore a program or application the memory changes from what's in Memory Usage to VM size.

Is memory leak possible in C#?

If you have many of those your application takes a lot of memory and eventually you run out of it. In C#, these are some common memory leaks: Not removing event listeners. Any event listener that is created with an anonymous method or lambda expression that references an outside object will keep those objects alive.


1 Answers

This blog post lists the most common situations that cause memory leaks in WPF applications.

  • Event handlers to objects in parent windows
  • Registering to events from static objects
  • Using timers
  • Data binding
  • Changing the Text property of a text box

It also describes how to fix these common issues.

Another good approach is to develop an app while following the standard guidelines and then use some kind of profiler to determine any memory leaks or performance bottlenecks.

like image 70
Haris Hasan Avatar answered Sep 21 '22 15:09

Haris Hasan