Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leaks in a Windows Forms application

We are developing a big .NET Windows Forms application. We are facing a memory leak/usage problem in that despite we are disposing the forms.

The scenario is like:

  1. Our application is using 60 KB of memory with a list of records displaying in a grid.
  2. When the user clicks on a record it opens a form, myform.showDialog, show the details. The memory jumps from 60 KB to 105 MB.
  3. Now we close the form myform to get back to grid, and dispose that form and set it to null. Memory remains at 105 MB.
  4. Now if we again perform step 2, it would jump from 105 MB to 150 MB and so on.

How can we free up the memory when we close myForm?

We have already tried GC.Collect(), etc., but without any result.

like image 315
Kashif Avatar asked Oct 08 '10 14:10

Kashif


People also ask

What is a memory leak in an application?

Description. Memory leaks are a class of bugs where the application fails to release memory when no longer needed. Over time, memory leaks affect the performance of both the particular application as well as the operating system. A large leak might result in unacceptable response times due to excessive paging.

How can Windows detect memory leaks?

Yes, there is a tool to analyze memory leaks.NET Memory Profiler. It is great to analyze memory leaks during development. It uses the concept of snapshots to compare new instances, disposed instances etc. This is a great help to understand how your service uses its memory.

Where is memory leak in .NET application?

Start the debug diagnostic tool and select 'Memory and handle leak' and click next. Select the process in which you want to detect memory leak. Finally select 'Activate the rule now'. Now let the application run and 'Debugdiag' tool will run at the backend monitoring memory issues.


2 Answers

The first place to look for leaks is in event-handling rather than missing Dispose() calls. Say your container (the parent form) loads a child form and adds a handler for an event of that child form (ChildForm.CloseMe).

If the child form is intended to be cleared from memory then this event handler must be removed before it is a candidate for garbage collection.

like image 188
STW Avatar answered Oct 02 '22 19:10

STW


Disposing the forms is not necessarily a guarantee that you are not leaking memory. For example, if you are binding it to a dataset but you are not disposing of the dataset when you are done, you will probably have a leak. You may need to use a profiling tool to identify which disposable resources are not being released.

And btw, calling GC.Collect() is a bad idea. Just saying.

like image 12
Otávio Décio Avatar answered Oct 02 '22 18:10

Otávio Décio