Saturday, February 25, 2012

Releasing Memory used in Windows Form Application Using C#


How to release memory used by an application - C#


Hi friends this is very common problem which we face while doing operation with very large objects



Some time we need to do operation with huge amount of binary data or some custom graphics drawing to do the needful things in our application.
If we don’t have sufficient memory to run our application we need to dispose unused objects from our application.
We usually write finally block in our program to release unused object or indirectly calls Garbage collector but it does not release the actually memory.

Usually in windows application memory is associated with process. If you kill you process your memory get released. But suppose we are doing operation like uploading bulk documents to database which has size around 2 to 3 GB then it fails to upload document to database, because each time binary object is created to convert physical document in to binary form to write in database.
This Issue is solved by Flushing memory by doing a bit of code:
Lets see how to do it.:
First you need to include following Two namespaces:
Using Microsoft.Win32;
Using System.Runtime.InteropServices;
It’s up to you to create a separate code file or include the Flush method in the same class where you are dong memory consumption operation:
My advice is to create a separate class so that you can use it anywhere in your application if you mostly do such type of operation.
Add following class in your solution: 
public class ReleaseMemory
{
[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);
}
}
Next call FlushMemory() method from you class to dispose or release unused memory
Eg: ReleaseMemory.FlushMemory();
It is a static method so don’t need any object of ReleaseMemory() class.

Feel free to write you suggestion 
Happy coding
Best Regards
Gireesh Painuly

7 comments:

  1. thanks gireesh its very help full

    ReplyDelete
  2. Thanks a lot.. This solution helps me a lot...

    ReplyDelete
  3. This code helps me a lot . Thank u

    ReplyDelete
  4. this solution hangs the app in windows 10 or 7

    ReplyDelete
  5. Just wanted to thank you. I know it is an old post but your ReleaseMemory class was the answer I was looking for. Thanks again!

    ReplyDelete