How to recycle memory for. NET Framework-based Windows Applications

Source: Internet
Author: User
For. NET Framework-based Windows applications, you will find that the more you operate on the program,
Memory usage will soar, even if you have finished running for a long time. This is the case for a very small application.
This situation is generally not caused by. Net Memory leakage, but because. Net does not immediately recycle your allocated memory. Below is a piece of code from a friend,
It can help you recycle memory instantly.

Public class RevokeMemory
{
Public static void export cememoryfootprint ()
{
Int currentMinWorkingSetValue = 0;
Int currentMaxWorkingSetValue = 0;
Process currentProcess = Process. GetCurrentProcess ();

Try
{
If (GetProcessWorkingSetSize (currentProcess. Handle, out currentMinWorkingSetValue, out currentMaxWorkingSetValue ))
{
CurrentProcess. MinWorkingSet = (IntPtr) currentMinWorkingSetValue;
}
}
Catch (Exception err)
{
String additionalInfo = "MinWorkingSet value is set to:" + currentMinWorkingSetValue. ToString ();
AdditionalInfo + = "Process In Error:" + currentProcess. ProcessName;
// Log error message
}
}

[DllImport ("kernel32.dll")]
Public static extern bool GetProcessWorkingSetSize (IntPtr proc, out int min, out int max );

[DllImport ("kernel32.dll")]
Public static extern bool SetProcessWorkingSetSize (IntPtr proc, int min, int max );

}

Call time:
1. Make a timer on the main interface and call each timer at a certain interval. However, I think this effect is not good. Before you perform a long-running operation. Disable it.
2. Each time a large operation or memory-consuming operation is completed, it is called.
I did a test. In the past, the memory usage soared, and the total memory consumption is between several megabytes and 30 megabytes.
If you don't believe it, you can try it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.