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;
}
Run Code Online (Sandbox Code Playgroud)
当我每300毫秒使用Timer并调用该Draw()方法时,一切正常,但是当我查看流程管理器时,我的项目使用了更多的内存(内存每300毫秒增加一次)
也许我应该使用垃圾收集器或使用垃圾收集器p = null;。如何解决此问题?
感谢您的帮助,对不起我的英语不好。
您从不丢弃Graphics对象。
使用using,例如:
using (Graphics gr = Graphics.FromImage(image)) {
...
}
pcImageBox.Image = image;
Run Code Online (Sandbox Code Playgroud)
另外,不要在Bitmap每个框架上都创建一个全新的框架。将旧的保存在成员变量中,并在下一次调用时使用它。仅当屏幕尺寸更改(Screen.PrimaryScreen.Bounds != image.Size)时才进行更换。