处理System.Drawing对象 [英] Disposing of System.Drawing Objects

查看:101
本文介绍了处理System.Drawing对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有必要手动管理System.Drawing对象的生命周期?

Is it necessary to manually manage the lifetime of System.Drawing objects?

目前,我正在使用'using'语句来最小化画笔和其他绘图对象的使用寿命例如

Currently I am employing 'using' statements to minimise the lifespan of Brushes and other Drawing objects e.g.

using ( Brush br = new SolidBrush( color ) )
{
    // Do something with br
}

这是必要的还是安全的让垃圾收集器发挥它的魔力什么时候以及是否需要?

Is this necessary or is it safe to let the garbage collector work its magic when and if it needs to?

作为一个快速抛开这个问题的人......人们认为什么是最简单的方法来实现这一目标?

As a quick aside to the question... what do people think is the cleanest way to achieve this?

推荐答案

处理System.Drawing对象是很好的,但是如果在得到异常时丢失一两个等等,这不是世界末日。 (像打开的文件和数据库连接之类的其他对象必须始终处于状态)

It is good to Dispose of System.Drawing object, however if you miss one or two when you get an exception etc, it is not the end of the world. (Other objects like opened files and database connections must always be disposed)

在代码中添加大量的使用复杂的理解。因此,在System.Drawing对象的情况下,考虑在方法的末尾调用Dispose()。

Having lots of "Using" statement all over your code make it more complex to understand. I would therefore in the case of System.Drawing object, consider just calling Dispose() on them at the end of the method.

In过去我使用过一个我写的Dustcart类,它实现了IDisposable,并且包含了要处理的对象集合。然后你可以编写如下代码:

In the past I have used a class I written "Dustcart", that implements IDisposable, and contains a collection of objects to dispose. You can then write code like:

using(var dustcart = new Dustcard())
{
   var p = dustcart.Add(new Pen(red, etc));
   var b = dustcart.Add(new Brush(black));

   Pen t;
   if (someFlag)
   {
      t = p;
   }
   else
   {
      t = dustcard.Add(new Pen(etc));
   }
}

这篇关于处理System.Drawing对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆