最近写一个监测程序,运行发现程序内存总是占用在15M左右,由于程序用来监测,所以感觉这么多内存被它占用着很是不好,GOOGLE了很久,又BAIDU了一下,大家都认为只要程序写的没有问题,占用这些内存是正常的,如果一定要减少,或者叫制作一个假象,那么最多用的方法就是使用API的 SetProcessWorkingSetSize ,
<揭穿号称内存占用极低的软件的诡计>一文中提供的方法:
PrivateDeclareFunctionSetProcessWorkingSetSizeLib"kernel32"(ByValhProcessAsLong,ByValdwMinimumWorkingSetSizeAsLong,ByValdwMaximumWorkingSetSizeAsLong)AsLong
PrivateDeclareFunctionGetCurrentProcessLib"kernel32"()AsLong
PrivateSubTimer1_Timer()
SetProcessWorkingSetSize GetCurrentProcess(),50000,100000
EndSub
但是在我使用中却无效,开始想到参数ByValhProcessAsLong可能有问题,但是又不知道如何修改,最后查了很多地方,发现在pinvoke上对API的参数设置为Private Declare Function SetProcessWorkingSetSize Lib "kernel32.dll" (ByVal hProcess As IntPtr, ByVal dwMinimumWorkingSetSize As Int32, ByVal dwMaximumWorkingSetSize As Int32) As Int32,按照他上面给的哪个方法,测试了以下,果然,效果明显,呵呵
暂时就这么用了
pinvoke地址:
http://www.pinvoke.net/default.aspx/kernel32.SetProcessWorkingSetSize
原文:(收藏学习了)
Summary
C# Signature:
[DllImport("kernel32.dll")]
static extern bool SetProcessWorkingSetSize(IntPtr hProcess, UIntPtr
dwMinimumWorkingSetSize, UIntPtr dwMaximumWorkingSetSize);
VB.NET Signature:
Private Declare Function SetProcessWorkingSetSize Lib "kernel32.dll" (ByVal hProcess As IntPtr, ByVal dwMinimumWorkingSetSize As Int32, ByVal dwMaximumWorkingSetSize As Int32) As Int32
User-Defined Types:
None.
Notes:
None.
Tips & Tricks:
Might be better written using int instead of UInt as -1 is a valid value for dwMaximumWorkingSetSize and dwMinimumWorkingSetSize. See Sample Code.
Sample Code:
//sample is probably a bad idea, but it will "trim down" the memory footprint of a .Net App (or at least the value reflected in Task Manager).
C#
public class MemoryManagement{
[DllImport("kernel32.dll")]
public static extern bool SetProcessWorkingSetSize( IntPtr proc, int min, int max );
public void FlushMemory() {
GC.Collect() ;
GC.WaitForPendingFinalizers() ;
if(Environment.OSVersion.Platform == PlatformID.Win32NT) {
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1) ;
}
}
}
VB.NET
Friend Sub ReleaseMemory()
Try
GC.Collect()
GC.WaitForPendingFinalizers()
If Environment.OSVersion.Platform = PlatformID.Win32NT Then
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1)
End If
Catch
End Try
End Sub