Control the memory usage of the C # Program

Source: Internet
Author: User
Destroy unnecessary data as soon as possible to reclaim memory usage. If COM components and databases are called, close them in time to avoid resource leakage. In fact, the. net program occupies normal memory, and you can ignore it if you are sure there is no leakage. Here is a temporary solution to reduce memory usage using APIs: [DllImport ("kernel32", EntryPoint = "SetProcessWorkingSetSize", ExactSpelling = true, CharSet = CharSet. ansi, SetLastError = true)] public static extern int SetProcessWorkingSetSize (int hProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize); Call method: SetProcessWorkingSetSize (System. diagnostics. process. getCurrentProcess (). handle. toInt32 (),-1,-1 );
 
 
In applications, some functions are often used to release memory. In fact, the memory operation functions should be used with caution. For example, the SetProcessWorkingSetSize that people often think of is actually for windows, the system will automatically release the memory when the program is idle (such as the program is minimized). When you release the memory, it will often cause some inexplicable memory errors, this causes unstable applications and systems.

The specific principles have been clearly written. The following are some posts for your reference:
========================================================== =====
1. Move physical memory usage to virtual memory ----- uncover
Move physical memory usage to virtual memory ----- uncover
See VB (or any program) to move physical memory usage to virtual memory

So why can my program move the occupied memory to the virtual memory?

Actually, you can also try to minimize a program to the taskbar, and then look at the task manager. No, the actual memory occupied by your program is suddenly reduced, it seems that I don't have any way to compress the memory, but the operating system itself has this mechanism, that is, when the program is not in use (minimized), the operating system will call some commands, to move the memory occupied by the program to the virtual memory and retain only a small portion of the common code.

So we can see that the memory usage is reduced at once.

So: what commands did the system call? Can I release the memory without narrowing down the form?

Look at this API SetProcessWorkingSetSize

This is the original answer from MSDN.

Using the SetProcessWorkingSetSize function to set an applications minimum and maximum working set sizes does not guarantee that the requested memory will be reserved, or that it will remain resident at all times. when the application is idle, or a low-memory situation causes a demand for memory, the operating system can reduce the applications working set. an application can use the VirtualLock function to lock ranges of the applications virtual address space in memory; however, that can potentially degrade the performance of the system.

Use this function to set the minimum and maximum runtime space of the application, and only reserve the required memory. When the application is idle or the system memory is too low, the operating system will automatically call this mechanism to set the application memory. Applications can also use VirtualLock to lock a certain range of memory from being released by the system.

When you increase the working set size of an application, you are taking away physical memory from the rest of the system. this can degrade the performance of other applications and the system as a whole. it can also lead to failures of operations that require physical memory to be present; for example, creating processes, threads, and kernel pool. thus, you must use the SetProcessWorkingSetSize function carefully. you must always consider the performance of the whole system when you are designing an application.

When you increase the runtime space for applications, the physical memory you can obtain depends on the system, which may cause other applications to degrade performance or the overall system performance, this may also cause the request to the physical memory operation to fail. For example, to create a process, thread, or kernel pool, you must use this function with caution.

======================================

In fact, using this function does not improve performance or actually save memory.

Because it only temporarily moves the memory occupied by the application to the virtual memory. Once the application is activated or has an operation request, the memory will be occupied again. If you use this method to set the memory occupied by the program, the system performance may be reduced to some extent because the system needs to frequently perform page exchanges between the memory and the hard disk.


BOOL SetProcessWorkingSetSize (
HANDLE hProcess,
SIZE_T dwMinimumWorkingSetSize,
SIZE_T dwMaximumWorkingSetSize
);


Set the two SIZE_T parameters to-1, that is, the memory used by the process can be switched to the virtual memory, only a small part of the code is retained.

The reason why the table calendar show can always keep the Minimum Memory is that the timer is used and the operation is not stopped. Therefore, the performance can be imagined. Although it is in exchange for the illusion of small memory, it is indeed a disaster for the system.

Of course, this function is not all right,

1. When our application is just loaded, you can use this operation once to put the code not required in the loading process into the virtual memory. In this way, after the program is loaded, maintain a large amount of available memory. VB

2. When the program runs for a certain period of time or the program is about to be idle, you can use this command to swap the occupied memory to the virtual memory.


Finally, attach the API code called by VB

Option Explicit
Private Declare Function SetProcessWorkingSetSize Lib kernel32 (ByVal hProcess As Long, ByVal dwMinimumWorkingSetSize As Long, ByVal dwMaximumWorkingSetSize As Long) As Long
Private Declare Function GetCurrentProcess Lib kernel32 () As Long

SetProcessWorkingSetSize GetCurrentProcess,-1,-1

Place the memory used by the current process to 0.

2. memory usage in. net
Today, we started to solve the problem of excessive system memory usage.

When we started the system last year, we found that the system occupied a large amount of memory. By June this year, the system started and occupied 60 MB of memory, after running for a period of time, it reaches about MB (the result of monitoring by the task manager). At that time, there are no solutions (including GC. collect, destructor, etc.), and later discussed with the source of inspiration on MSN, he thought it may be the problem of using MagicLibrary in the system, so it was put on hold.

I found my blog on the Internet and some people have discussed it. Zhiqiu yiye gave a wonderful explanation. After reading it, I felt a sense of excitement. In the system, the SetProcessWorkingSetSize method is used for a test. After this method is called, the occupied memory is reduced from 80 Mb to 2 MB. (results observed by TaskManager) According to Zhiqiu yiye, adjusting WorkingSet may lead to page-missing interruptions, seriously affecting performance. However, from the usage perspective, we have not found such a phenomenon. This may be the reason why I use this method:


Public static int MinOf (uint pID)
{
IntPtr hd = OpenProcess (uint) PROCESS_ACCESS_RIGHTS.PROCESS_SET_QUOTA, false, pID );

Try
{
If (hd! = IntPtr. Zero System. Environment. OSVersion. Platform = System. PlatformID. Win32NT)
{
Return SetProcessWorkingSetSize (hd,-1,-1 );
}
Else
{
Return-1;
}
}
Finally
{
CloseHandle (hd );
}
}
The above Code comes from http://www.zpcity.com/ArLi//commonprj/cls_MinWorkSize.cs

According to Zhiqiu yiye, the system does not make much sense to adjust the WorkingSet in this way. However, it is not very nice to look at the numbers in taskmanager.
Some comments in this article:
// After multiple tests, it is found that using the SetProcessWorkingSetSize method may indeed cause system instability.
//. Net gc is trustworthy, as long as the code specification is enough
//

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.