3

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

myPictureBox.Image = GetBiorhythm2();

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

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

导致错误的缩减函数是:

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;
 }

如果我注释掉刷子处理它可以正常工作,但我对此不满意并希望找到替代解决方案。你能帮我吗 ?

4

3 回答 3

14

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

Brushes 类的文档说:

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

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

于 2009-01-23T02:45:17.303 回答
11

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

    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.

当您设置画笔 = 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(); 注释掉即可。行在您的原始代码中。

于 2009-01-23T02:46:04.273 回答
3

我认为您不需要在静态画笔上调用 .Dispose ,除非您创建新画笔。虽然,就个人而言,我会使用 using 语法.. 即:

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

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

于 2009-01-23T02:25:46.280 回答