DrawToBitmap - System.ArgumentException:参数无效

mir*_*iri 5 .net c# system.drawing bitmap

我创造了一个Label,有时我正在使用.DrawToBitmap().我不知道为什么,但在我运行我的程序一段时间后(.DrawToBitmap()经常调用)我得到了异常:

System.ArgumentException: Parameter is not valid.
   at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
   at System.Drawing.Bitmap..ctor(Int32 width, Int32 height)
Run Code Online (Sandbox Code Playgroud)

不知怎的,我不能经常调用这个函数.如果我从根本上尝试这个:

while(true)
{

  System.Windows.Forms.Label label = new Label();

  label.Font = new Font("Arial", 20);
  label.Text = "test";

  try
  {
    Bitmap image = new Bitmap(300, 500);
    label.DrawToBitmap(image, label.ClientRectangle);
  }
  catch (Exception e)
  {
    Console.WriteLine(e);
  }
}
Run Code Online (Sandbox Code Playgroud)

我得到了5-6秒(1000-2000个电话)的异常.问题是什么?怎么避免这个?

编辑:谢谢你们的想法Dispose()- 不知何故,如果我使用它,一切都很完美label.即使我不在Bitmap上使用它也没关系.这两个答案都很棒,我只能接受其中一个:(

Ed *_* S. 6

因此,该错误消息来自GDI +的内心深处,可能出现很多原因.我看到你的代码有一个明显的问题,但是:

 label.Font = new Font("Arial", 20);
Run Code Online (Sandbox Code Playgroud)

Font对象实现IDisposable,你在紧密循环中创建了很多对象,从不调用Dispose().Bitmap本身也是如此.我敢打赌,GDI资源不足.

现在很难理解你的代码.它本质上绝对没有,但创建吨FontBitmap对象,所以我不能甚至建议每个包裹这些声明的一个using声明.除此之外,当你快速连续创建大量GDI对象而不处理它们时,你最终会遇到这个问题.

如果您需要这些对象有效一段时间,那么您需要确保Dispose()稍后调用它们以尽可能及时地释放本机资源(终结器将为您执行此操作,但最好不要等待它至).如果它们是本地对象,则将它们包装在using语句中,以便Dispose()在块退出时调用它们:

using(var b = new Bitmap(w, h))
{
    // use 'b' for whatever
} // b.Dispose() is called for you
Run Code Online (Sandbox Code Playgroud)