Showing posts with label GC.Collect. Show all posts
Showing posts with label GC.Collect. Show all posts

Thursday, February 07, 2008

Release memory in Windows Form application using C#

Windows Form applications (Microsoft.Net Desktop applications) sometimes start consuming a lot of memory, which has different drawbacks, but I'll not get into the details of them here. What we'll look into is how to avoid the excess use of the memory resource in a windows application in C#.

In fact, you need to flush memory to release all the unused memory to make more space available for your current and other applications. First of all include following two namespaces:

using Microsoft.Win32;
using System.Runtime.InteropServices;

and then use the following code snippet to flush excesssive use of memory. You can view the currently consumed memory by viewing the application process name in the currently running processes list. For that purpose just go to the Task Manager, and then go to Processes tab and find out your application's process.

Following code imports a win32 dll and flushes the memory. But, before that it also uses Microsoft.Net's garbage collector to force an immidiate garbage collection:

public class MemoryManagement
{
[DllImportAttribute("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet =
CharSet.Ansi, SetLastError = true)]

private static extern int SetProcessWorkingSetSize(IntPtr process, int minimumWorkingSetSize, int
maximumWorkingSetSize);

public static void FlushMemory()
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (Environment.OSVersion.Platform == PlatformID.Win32NT) { SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
}

copy and use this class in your code and have fun reducing the memory size!