它是重要的处置SolidBrush和笔​​?它是、重要、SolidBrush

2023-09-03 02:25:57 作者:半岛旧梦

我最近碰到在$此VerticalLabel控制C $的CProject

我注意到OnPaint方法创建,但不配置笔和SolidBrush对象。

I notice that the OnPaint method creates but doesn't dispose Pen and SolidBrush objects.

这有关系,如果是这样我怎么能证明任何问题,它可能会导致?

Does this matter, and if so how can I demonstrate whatever problems it can cause?

修改

这是不是一个整体信息IDisposable模式的问题。据我所知,来电者通常应调用Dispose实现IDisposable的任何类。

This isn't a question about the IDisposable pattern in general. I understand that callers should normally call Dispose on any class that implements IDisposable.

我想知道的是什么的问题(如果有的话)可以预期当GDI +对象没有设置如在上面的例子。很明显,在链接的例子,OnPaint中可以被称为很多次垃圾收集踢,所以有用完手柄的潜力。

What I want to know is what problems (if any) can be expected when GDI+ object are not disposed as in the above example. It's clear that, in the linked example, OnPaint may be called many times before the garbage collector kicks in, so there's the potential to run out of handles.

不过,我怀疑GDI +(如果你使用的笔类特定颜色的笔,它被缓存和重用为例)内重复使用的手柄在某些情况下。

However I suspect that GDI+ internally reuses handles in some circumstances (for example if you use a pen of a specific color from the Pens class, it is cached and reused).

我试图理解的是code一样,在链接的例子是否可以逃脱忽略调用Dispose。

What I'm trying to understand is whether code like that in the linked example will be able to get away with neglecting to call Dispose.

如果不是,看一个示例,展示了什么问题它可以导致。

And if not, to see a sample that demonstrated what problems it can cause.

我要补充一点,我有很多时候(包括MSDN 的OnPaint中的文件)看到的WinForms $未能处置GDI +画线C $ C样本。

I should add that I have very often (including the OnPaint documentation on MSDN) seen WinForms code samples that fail to dispose GDI+ objects.

推荐答案

当然,这非常重要。它处置实现IDisposable的时候不再需要他们班所有的实例是很重要的。类中定义了IDisposable时,他们利用非托管资源,也就是不受.NET Framework的处理操作系统资源。

Of course it does matter. It is important to dispose all instances of classes that implement IDisposable when they are no longer needed. Classes are defined IDisposable when they make use of unmanaged resources, that is, operating system resources that are not handled by the .NET Framework.

如果您没有手动配置的对象,那么这些非托管资源不会被释放,直到垃圾回收器调用对象的终结(这将该类是否正确实施的的Dispose模式),这可能是很晚了,因为垃圾收集器只检测一个实际的内存不足时运行。因此,当未处置的对象,则是保留操作系统资源本来可用于其他的应用程序。

If you don't manually dispose the objects, then these unmanaged resources will not be freed until the garbage collector invokes the object finalizer (and this will only happen if the class has properly implemented the Dispose pattern), which may be very late since the garbage collector only runs when it detects an actual memory shortage. Thus when not disposing objects, you are retaining operating system resources that could otherwise be used by other applications.

关于这个问题的讨论可以在这里找到:的 http://agilology.blogspot.com/2009/01/why-dispose-is-necessary-and-other.html

A discussion on this subject can be found here: http://agilology.blogspot.com/2009/01/why-dispose-is-necessary-and-other.html