处理静电刷

我正在写一个生物节律应用程序。 为了测试它,我有一个带有Button和PictureBox的表单。 当我点击按钮时,我做了

myPictureBox.Image = GetBiorhythm2(); 

哪个第一次运行正常, 但在第二次单击时会导致以下exception:

 System.ArgumentException: Parameter is not valid. at System.Drawing.Graphics.CheckErrorStatus at System.Drawing.Graphics.FillEllipse at Larifari.Biorhythm.Biorhythm.GetBiorhythm2 in c:\delo\Horoskop\Biorhythm.cs:line 157 at Larifari.test.Button1Click in c:\delo\Horoskop\test.Designer.cs:line 169 at System.Windows.Forms.Control.OnClick at System.Windows.Forms.Button.OnClick at System.Windows.Forms.Button.OnMouseUp at System.Windows.Forms.Control.WmMouseUp at System.Windows.Forms.Control.WndProc at System.Windows.Forms.ButtonBase.WndProc at System.Windows.Forms.Button.WndProc at ControlNativeWindow.OnMessage at ControlNativeWindow.WndProc at System.Windows.Forms.NativeWindow.DebuggableCallback at ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop at ThreadContext.RunMessageLoopInner at ThreadContext.RunMessageLoop at System.Windows.Forms.Application.Run at Larifari.test.Main in c:\delo\Horoskop\test.cs:line 20 

导致错误的减少function是:

 public static Image GetBiorhythm2() { Bitmap bmp = new Bitmap(600, 300); Image img = bmp; Graphics g = Graphics.FromImage(img); Brush brush = Brushes.Black; g.FillEllipse(brush, 3, 3, 2, 2); //Here the exception is thrown on the second call to the function brush.Dispose(); //If i comment this out, it works ok. return img; } 

如果我评论出画笔处理它可以正常工作,但我对此并不满意,并希望找到另一种解决方案。 你能帮我吗 ?

看起来你正在尝试处理静态,这会在下次使用时导致一些问题:

  Brush brush = Brushes.Black; g.FillEllipse(brush, 3, 3, 2, 2); //Here the exception is thrown on the second call to the function brush.Dispose(); //If i comment this out, it works ok. 

当你设置brush = Brushes.Black时,你实际上是将画笔设置为静态Brushes.Black的引用(或指针)。 处理它,你有效地写:

  Brushes.Black.dispose(); 

当你回来再次使用黑色画笔时,运行时说你不能,因为它已经被处理掉了,并且不是g.FillEllipse()的有效参数

写这个的更好方法可能只是:

  g.FillEllipse(Brushes.Black, 3, 3, 2, 2); 

或者,如果你想要真的很复杂:

  Brush brush = Brushes.Black.Clone(); g.FillEllipse( brush, 3, 3, 2, 2 ); brush.Dispose(); 

或者如果你不关心看起来错误的东西,只需注释掉brush.Dispose(); 原始代码中的行。

Bruhes.Black是一种系统资源,不适合您处置。 运行时管理Brushes类,Pens和其他此类对象中的画笔。 它根据需要创建和处理这些对象,使常用项目保持活动状态,以便不必持续创建和销毁它们。

Brushes类的文档说:

Brushes类包含静态只读属性,这些属性返回由属性名称指示的颜色的Brush对象。 除非用于构造新画笔,否则通常不必显式处理此类中的属性返回的画笔。

简而言之,不要在系统提供的对象上调用Dispose。

我认为你不需要打电话。只有在创建新画笔时才会在静态画笔上使用。 虽然,就个人而言,我会使用using语法..即:

 using (Brush brush = new SolidBrush(...)) { g.FillEllipse(brush, 3, 3, 2, 2); } 

你可能应该对你创建的图形对象做同样的事情。