Search This Blog

Thursday 20 December 2012

Memory Cleaner that forces GC to collect objects in asp.net or Wcf or Window service

The following example demonstrates how to use the Collect method to perform a collection on all generations of memory. The code generates a number of unused objects, and then calls the Collect method to clean them from memory.

[DllImportAttribute("Kernel32.dll", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
    private static extern int ProcessWorkingSetSize(IntPtr Process, int minimumWorkingSetSize, int maximumWorkingSetSize);
    public void Flushmemory()
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        if (Environment.OSVersion.Platform == PlatformID.Win32NT)
        {
            ProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
        }
    }

No comments:

Post a Comment