SetProcessWorkingSetSize

最近写一个监测程序,运行发现程序内存总是占用在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    

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值