继续上一篇的解释:
--------------------------------
一个空白WinForm在任务管理器中都占用几十兆内存,的确有点可怕!通常有3种方法:
1. 不要管他。
CLR & GC 会自动管理内存占用,根据当前环境参数自动调整,这样会得到一个最佳化的运行效率。
2. 设置托管程序进程允许的最大工作集大小。
3. 使用SetProcessWorkingSetSize,将部分物理内存占用转移到虚拟内存。
2 public static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max );
3
4 private void button1_Click( object sender, System.EventArgs e)
5 {
6 SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, - 1 , - 1 );
7 }
注意第2,3种方法在某种程度上都会影响程序的性能。设置一个合理的工作集大小,或者在程序启动后,空闲时(Application.Idle)使用SetProcessWorkingSetSize,还是可以的,毕竟减少内存占用对于系统运行也有一定的益处。
使用事例:
1
private
void
timer1_Tick(
object
sender, System.EventArgs e)
2
{
3
//
使用定时器将当前物理内存占用(MB)添加到列表框中。
4
string
s
=
string
.Format(
"
{0}
"
, Process.GetCurrentProcess().WorkingSet
/
1024
/
1024
);
5
this
.listBox1.Items.Insert(
0
, s);
6
}
7
8
[DllImport(
"
kernel32.dll
"
)]
9
public
static
extern
bool
SetProcessWorkingSetSize(IntPtr proc,
int
min,
int
max );
10
11
private
void
button1_Click(
object
sender, System.EventArgs e)
12
{
13
//
减少内存占用
14
SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle,
-
1
,
-
1
);
15
}