.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

How to detect and avoid memory and resources leaks in .NET application

Posted By: Venkat     Posted Date: February 03, 2010    Points: 2   Category :.NET Framework
Despite what a lot of people believe, it's easy to introduce memory and resources leaks in .NET applications. The Garbage Collector, or GC for close friends, is not a magician who would completely relieve you from taking care of your memory and resources consumption.

I'll explain in this article why memory leaks exist in .NET and how to avoid them. Don't worry, I won't focus here on the inner workings of the garbage collector and other advanced characteristics of memory and resources management in .NET.

View Complete Post

More Related Resource Links

Debug Leaky Apps: Identify And Prevent Memory Leaks In Managed Code


When is the .NET Garbage Collector unable to reclaim memory? The answer might surprise you. Stay tuned.

James Kovacs

MSDN Magazine January 2007

No More Hangs: Advanced Techniques To Avoid And Detect Deadlocks In .NET Apps


You can combat deadlock using a combination of disciplined locking practices which Joe Duffy aptly explains in this article.

Joe Duffy

MSDN Magazine April 2006

Visual C++ 6.0: Don't Let Memory Allocation Failures Crash Your Legacy STL Application


Most C++ developers make extensive use of the Standard Template Library (STL) in their code. If you are one of them and are using STL and Visual C++ 6.0 directly out of the box, your application is at high risk of crashing under low memory conditions. The problem arises because checking for failure of operator new is such an uncommon practice. To make things worse, when new does fail, the response is not standard. Some language compilers return NULL while others throw an exception.In addition, if you are using STL in an MFC project, be aware that MFC has its own set of rules. This article discusses these problems, explains how the default behavior has changed in Visual C++ .NET 2003, and outlines the changes you must make if you're using Visual C++ 6.0 so that you can safely use the STL when operator new fails.

James Hebben

MSDN Magazine September 2003

Debug: Detect and Plug GDI Leaks in Your Code with Two Powerful Tools for Windows XP


In a previous article, the author devised a simple method to detect Graphical Device Interface (GDI) objects that are not properly released by Win32-based applications on Windows 9x platforms. Because some newer versions of Windows require a slightly different approach to GDI leaks, the author has updated his techniques for those operating systems. He builds and explains two tools designed to detect and eradicate GDI leaks in applications running on Windows XP, Windows 2000, and Windows NT.

Christophe Nasarre

MSDN Magazine January 2003

Binding byte[] to image control in navigation application leaks

Hi there, I have a (minimal) navigation application with two pages. Page1 contains an image. Switching between pages is done via a buttonhandler in code behind, for instance, (this.NavigationService.Navigate(new Page2())) The image is loaded in code behind via: private void LoadImage() { string fileName = "./images/image.bmp"; if (!new FileInfo(fileName).Exists) throw new Exception("File name doesn't exist"); using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { this.ImageData2 = new byte[fs.Length]; fs.Read(this.ImageData2, 0, System.Convert.ToInt32(fs.Length)); fs.Close(); } } ImageData2 is a byte[] property that sends a propertychange event on changing. ImageData2 is bound to an image in xaml: <Image Grid.Row="1" Source="{Binding Path=ImageData2, Mode=OneTime}"/> When we unload Page1 the following clean up code is executed private void Page_Unloaded(object sender, RoutedEventArgs e) { this.ImageData2 = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); } Now, when I start changing pages, I expect the Page we leave to unload, so the GC removes the byte array. However, it doesn't. Am I missing something? Binding the image to a BitmapImage (ImageData1, as you might have guessed:-) ) doesn't leak.

memory leaks

Hi, I am trying to detect memory leaks...memory(RAM) keep goes up this is the code I am using, where dbManager is the DLL that holds all of the DAL Code (LINQ TO SQL) foreach (string lnk in splited_links) { unique_key = Helpers.FilterBadWords(lnk, new string[] { "http://www.", "-lcs.html" }); article = dbManager.GetArticleByUniqueKey(unique_key); if (article == null) { Match matchLyrics2 = reLyricsPage.Match(lnk); if (matchLyrics2.Success) { //do something } } } //IN THE DLL FILE public Tbh_Articles GetArticleByUniqueKey(string uniqueKey) { using (KaruselaDataContext ctx = new KaruselaDataContext(connection)) { //KaruselaDataContext ctx = new KaruselaDataContext(connecti

Accessing memory of a remote process (x64) from application (x86) - and the other way

Hi everyone, My program access a remote process, e.g. to get the text of ListViewItem. It uses ReadProcessMemory, WriteProcessMemory, SendMessage, LV_ITEM via PInvoke. Below is a little codesnippet. This doesnt work, when i compile for x86 and the remote process is x64 (or the other way). I know that is because the size of IntPtr - and so of the LV_ITEM-Structure - is different. Is there any way, to access x86 and x64 remote processes from the same application?  Is there any way to find out if the remote process is x86 or x64 and make my call's with a suitable LV-Item Structure? thanks Torsten Codesnippet: LV_ITEM lvitem = new LV_ITEM(); // Allocate memory in the remote process's address space string s = string.Empty; IntPtr pszTextMemory = VirtualAllocEx(hProcess,IntPtr.Zero,  1024, (int)(AllocationType.MEM_RESERVE|AllocationType.MEM_COMMIT), (int)(AccessProtectionType.PAGE_READWRITE)); lvitem.pszText = pszTextMemory; ... IntPtr pLVItemMemory = VirtualAllocEx(hProcess, IntPtr.Zero,  Marshal.SizeOf(lvitem), (int)(AllocationType.MEM_RESERVE|AllocationType.MEM_COMMIT), (int)(AccessProtectionType.PAGE_READWRITE)); IntPtr lvItemPtr = Marshal.AllocHGlobal(Marshal.SizeOf(lvitem)); Marshal.StructureToPtr(lvitem,lvItemPtr,false); WriteProcessMemory(hProcess, pLVItemMemory, ref lvitem, Marshal.SizeOf(lvitem), ref written); SendMessage(hListView, LVM_GETITEM

I'm detect as a Robot, how can I avoid this problem?

HiWhen i'm sending an HttpWebrequest, I've this response:"Go away, Robots are not supposed to visit this page" What can I do for avoid this?Thanks

WPF: how to detect application idle?

Our application uses WPF and touch screen. We need to detect application idle (no user interact with the application such as click buttons, however the application still running) for 10 minutes so we can take some action. How do we detect WPF application idle? thx!  

Install-SPSolution : This solution contains no resources scoped for a Web application and cannot be



What we want to achieve: install/deploy a custom site template ONCE so it becomes available to all site colls in several we apps. 

We have
1) modified a web site based on a Team Site template
2) saved the web site as a template (template is available in (site coll?) solution gallery)
3) saved the site template as a file
4) added the site template to the farm solution store using add-SPSolution

When we try to deploy the solution to a web app using Install-SPSolution we get the following error message:

"Install-SPSolution : This solution contains no resources scoped for a Web application and cannot be deployed to a particul
ar Web application."

Obviously we are missing something here.

Is the ONLY way to add/install the solution at the site coll level?

How to avoid the memory exhausion for handling large Image files in C# ?


I have been developing a Form application for handling a large number Image files. The number of Image files could be more than 1,000 and each Image size is about 2MB. The code is as follows:

PictureBox[] pb = new PictureBox[iPictureBoxNumMax];
Label[] lb = new Label[iPictureBoxNumMax];

for (int i = 0; i < iPictureBoxNum; i++)
    lb[i] = new Label();
    pb[i] = new PictureBox();
    pb[i].ImageLocation = @sImageListAll[i];


for (int i = 0; i < iPictureBoxNum; i++)

(1) If the number of Image files is less than 300, the PictureBox generation code (the 1st portion) works. If the number is larger than that, an error message of "Memory exhausion" is displayed.

(2) However, the second protion of the code (pb[i].Dispose()) doesn't seem to clear, since the re-run of the first portion gives an error message of "Memory exhausion".

What should I do ?


why do nothing .NET application allocates 500 MB virtual memory?


I'm wondering why an empty .NET console application (only has Console.WriteLine() and Console.ReadLine()) allocates 500 MB of virtual memory?  By the way, this is running on a dual core with hyperthreading.

The 500 MB is allocated when I compile with the 3.5.30729.4926 compiler and don't target any platform.  I'm running Windows 7 x64 so this 500 MB is for the 64 bit application.

If I compile with the 32 bit compiler, 8.00.50727.4927, the 32 bit application allocates 117 MB of virtual memory.



AJAX UpdatePanel Memory Leaks in IE.


After researching why a page I have using an UpdatePanel to perform a refresh every 15 seconds was using up piles and piles of memory over time, I discovered that this is a "well-known" issue with the UpdatePanel not cleaning up properly in IE (some issue with reference counting in COM interop or some such).  UpdatePanel does not seem to have this issue in Firefox (haven't confirmed the issue in other browsers).

If this is a "well-known" issue, two questions:

Is there a "well-known" workaround to this?  I know that a full-page refresh will cause the memory to be cleaned up, but some pages may be up for a long time and I don't want to interrupt any user interaction with the page that may be going on.  I will if it is required, but it is a sloppy, sloppy UI kluge... you know, one of those "as a self-respecting coder I hang my head in shame at what I have wrought" kind of kluges.

Is there any effort being made to fix this?  I've looked about, however, most articles on this do not make mention of even MS acknowledging bug status for this while I've seen many telling me why this is an issue, and how it's a "design" thing.  I hear IE9 is supposed to take care of this... I guess what you'd call a non-issue, but it will only be available to

WPF Memory leaks in a Huge Images list


I create a simple WPF application to display images in a child window from a folder.

this folder contains a huge number of images

After closing the child window that contains a virtualization tile panel and a data virtualization collection taken from this article the memory will not return as it was before opening the window.

I followed some steps mentioned in this article. but i still see some memory leaks! so could you please help me to find it.

- All of resources are frozen like this:


<Window ...



Marshaling : avoid native memory freeing



I have a little problem with marshaling.

I have a structure :



    public class virConnectCredential



        public virConnectCredentialType type;

        public IntPtr prompt;

        public IntPtr challenge;

        public IntPtr defresult;

        public IntPtr result;

        public uint resultlen;



the "result" member is a string. I have made the choice to pass strings between native and managed via IntPtr.


This structure is passed to a function via an IntPtr (In and Out). The goal is to fill the "result" member of the structure Like this :

private static int AuthCallback(IntPtr creds, UInt32 ncred, IntPtr cbdata)


virConnectCredential vcc = (virConnectCredential)Marshal.PtrToStructure(creds, typeof(virConnectCredential));

// Put toto in the result member

Serial Port Application Leaks Handle After Exit Forcing Reboot to Clear


The application (C# .Net 3.5) available at www.redondowa.com/porttest demonstrates a problem encountered with a Sony VAIO multimedia laptop related to use of its serial modem port.  A discussion with MS support is included in a doc with the VS solution.

If the base stream or port is not closed before nulling the port, the port cannot be recreated and the application leaves the port inaccessible.  The machine requires a reboot to clear the error.  Other machines clear the error without requiring a reboot.

<!-- /* Font Definitions */ @font-face {font-family:SimSun; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:"Arial Unicode MS"; mso-font-charset:134; mso-generic-font-family:roman; mso-font-format:other; mso-font-pitch:variable; mso-font-signature:1 135135232 16 0 262144 0;} @font-face {font-family:"Cambria Math"; panose-1:2 4 5 3 5 4 6 3 2 4; mso-font-charset:0; mso-generic-font-family:roman; mso-font-pitch:variable; mso-font-signature:-1610611985 1107304683 0 0 159 0;} @font-face {font-family:Calibri; panose-1:2 15 5 2 2 2 4 3 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:-1610611985 1073750139 0 0 159 0;} @font-face {font-family:"\@SimSun"; panose-1:0 0 0 0 0 0 0 0 0 0; mso-font-charset:134; mso-generic-font-family:roman; mso-font-format:other; mso-font-pitch

How to avoid buffering in memory even if I have already dispose the webs


When I try to connect to the sharepoint , the first time I use a valid account to login and then I use a invalid user to login. But  the invalid user also can get the data from sharepoint. Maybe this is caused by the memory buffering.

I use SPWeb::GetWebCollection();



ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend