Post

.NET Application Memory Flush via Interop - Revisited

As I’ve stated before, I do make mistakes ;-)

I have an application that I’ve written for my employer that appears, under certain unidentified circumstances to have a very slow memory leak. While trying to narrow down where it could be, I pulled one of my components out to test it with a console interface as a harness (to reduce the amount of outside memory being used) and leveraging the CLR Profiler (free) and the .NET Memory Profiler (14 day eval) to see what is happening. One of the things making this difficult, since I’m trying to look at native memory as well, is the effect that the framework has on the application and Windows reporting memory consumption. So I decided to add the memory flush method that I posted back in November 2003 to the mix. Even though I had several warnings around that code posting, there was one that wasn’t stated. Although it does do what is says, on the surface, there is a slight bloating effect inherent to it as well. In addition, it’s seriously overkill since it’s forcing a garbage collection. Here is an updated code listing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Public Class MemoryManagement
 
  Private Declare Function SetProcessWorkingSetSize Lib "kernel32.dll" ( _
    ByVal process As IntPtr, _
    ByVal minimumWorkingSetSize As Integer, _
    ByVal maximumWorkingSetSize As Integer) As Integer

  Public Shared Sub FlushMemory()
    'GC.Collect()
    'GC.WaitForPendingFinalizers()
    If (Environment.OSVersion.Platform = PlatformID.Win32NT) Then
      Dim p As Process = Process.GetCurrentProcess
      SetProcessWorkingSetSize(p.Handle, -1, -1)
      p.Dispose
    End If
  End Sub

End Class 

The problem with the previous version is that the GetCurrentProcess was creating a reference to a Process that was staying in memory until it’s finalizer would run during a GC0 (Garbage Collection level 0). By adding in the Dispose, you are removing the bloat by specifically telling the framework to release (what appears to be) the un-managed reference to a Process. Again, this wasn’t that big of a deal since we are talking about a relatively small amount of memory, but still… it was wrong… now it’s right. ;-)

As for forcing the GC, I don’t really think that it is necessary in order to get Windows to see the “true” memory consumption as described in the previous article. Also, it’s just not good .NET practice to do so… so it’s been removed.

Also, due to these modifications, the warnings in the previous article are no longer relevant… since we aren’t forcing a GC. The only warning now is the fact that you are using P/Invoke and have to adhere to whatever restrictions doing so incur.

This post is licensed under CC BY 4.0 by the author.