Saturday 21 November 2009

Great article about memory leaks in .NET application

When digging more information about GDI resource leaking I have found nice article which describes what memory leaks can be found in .NET applications and how to avoid them. The article also shows what tools can be used to find different kinds of leaks. Here is the link How to detect and avoid memory and resources leaks in .NET applications.

Tuesday 17 November 2009

GDI objects leaking and its prevention

Everyone who is developing WinForms applications can find out that his application starts in some point have problem with raising GDI objects count. Usually developers who use some high-level programming language (in my case c#) don't think they should care about releasing some low-level objects such as GDI objects but it's not true. It can happen that the application which is opening a lot of forms, creating its forms dynamically etc. will start to be slow and after some time even unusable.

What are GDI objects for?

Among GDI objects belong Bitmap, Brush, DC, Font, Palette and some other objects (see full list in the link section). These objects are used for visualization of UI of applications in Windows. Each version of Windows has maximum number of GDI objects which can be created in the moment (e.g. WinXP has default of 10000 objects set). The max number can be set in Windows registry. The actual amount of created objects per application can be displayed in task manager (show GDI objects column settings).

What is the problem?

Each time the application needs to show new form, GDI objects are created and if they are not properly disposed then their amount is raising, consuming memory and windows kernel starts to have problem with redrawing forms, creating new forms and whole system slows down.

What can developer do to prevent GDI objects count raising?

Developer should make sure that Dispose() method is called on all disposable objects. The biggest problem is when the form content is composed dynamically then Dispose() method needs to be called manually on all dynamically created controls. When application shows non-modal forms (use form.Show()) then developer doesn't need care about calling Dispose() method. But if the application shows modal dialogs (use dlg.ShowDialog()) then Dispose() needs to be called manually to free up created GDI resources.

Links:

GDI Objects on msdn
GDI on wikipedia
Detecting GDI user handler leaks in WinForms
Detect and Plug GDI Leaks in Your Code with Two Powerful Tools for Windows XP
GDI memory leak in Windows Forms