Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么使用的内存量在增加?_C#_Memory - Fatal编程技术网

C# 为什么使用的内存量在增加?

C# 为什么使用的内存量在增加?,c#,memory,C#,Memory,当我使用Timer并每隔300毫秒调用Draw()方法时,一切正常,但当我查看process manager时,我的项目使用了更多内存(内存每300毫秒增加一次) 也许我应该使用垃圾收集器或者使用p=null等。如何解决此问题 感谢您的帮助,并为我糟糕的英语表示歉意。您从未处理过您的图形对象 使用使用,如: private void Draw(){ int width = Screen.PrimaryScreen.Bounds.Width; int height = Scr

当我使用
Timer
并每隔300毫秒调用
Draw()
方法时,一切正常,但当我查看process manager时,我的项目使用了更多内存(内存每300毫秒增加一次)

也许我应该使用垃圾收集器或者使用
p=null等。如何解决此问题


感谢您的帮助,并为我糟糕的英语表示歉意。

您从未处理过您的
图形对象

使用
使用
,如:

private void Draw(){
     int width  = Screen.PrimaryScreen.Bounds.Width;
     int height = Screen.PrimaryScreen.Bounds.Height;
     Bitmap image= new Bitmap(width, height);
     Graphics gr =  Graphics.FromImage(image);
     gr.CopyFromScreen(0, 0, 0, 0, new Size(width, height));
     Random rnd = new Random();

     gr.DrawEllipse(new Pen(Color.Red, rnd.Next(100)), rnd.Next(300), rnd.Next(100), rnd.Next(600), rnd.Next(1000));
     Point[] p = new Point[3];
     p[0] = new Point(rnd.Next(30),  rnd.Next(60));
     p[1] = new Point(rnd.Next(100), rnd.Next(260));
     p[2] = new Point(rnd.Next(30),  rnd.Next(10));
     gr.DrawPolygon(Pens.AliceBlue, p);
     gr.DrawBeziers(Pens.Yellow, p);
     pcImageBox.Image = image;
}

另外,不要每帧创建一个全新的
位图。将旧的保存在成员变量中,并在下次调用时将其覆盖。仅当屏幕大小更改时才创建一个新的(
screen.PrimaryScreen.Bounds!=image.size
)。

更好的方法可能是:


@mellamokb:他应该做些什么来避免创建一堆未经分解的
位图
对象,但重用前一个对象可能比将其连接到
图片盒
时进行处理要好。旁注:您正在创建本地随机生成器,而不是使用共享的。在这种情况下是可以的(因为对Draw的调用之间的间隔超过10-20ms),但请检查您的其他代码,以便在频繁调用的方法中创建类似的Random。。。
using (Graphics gr =  Graphics.FromImage(image)) {
     ...
}
pcImageBox.Image = image;