在使用 Using 後清除(或至少 Dispose)
Graphics、Pen 和 Brush 對象都與相似類型的 Windows 對象相關聯。這些 Windows 對象分配在作業系統的記憶體中 -- 這些記憶體尚未被 .NET 運行時管理。長時間將這些對象駐留在記憶體中會導致效能問題,並且在 Microsoft Windows 98 下,當圖形堆填滿時會導致繪圖問題。因此,我們應儘快釋放這些 Windows 對象。
當相應的 .NET Framework 對象完成操作並回收記憶體後,.NET 運行時會自動釋放 Windows 對象。但回收記憶體的時間會很長 -- 如果我們不迅速釋放這些對象,所有不幸的事情(包括填滿 Windows 堆)都可能發生。在該應用程式的 ASP.NET 版本中,由於很多使用者在同一台伺服器上訪問該應用程式,所以這種現象會更加嚴重。
因為這些對象與未管理的資源相關聯,所以它們實現 IDisposable 介面。該介面有一個方法,即 Dispose,它將 .NET Framework 對象從 Windows 對象中分離出來,並釋放 Windows 對象,從而使電腦處於良好的狀態。
C#
public class DFilledCircle : DHollowCircle, IFillable
{
public DFilledCircle(Point center, int radius, Color penColor,
Color brushColor) : base(center, radius, penColor) {
this.brushColor = brushColor;
}
public void Fill(Graphics g) {
using (Brush b = new SolidBrush(brushColor)) {
g.FillEllipse(b, bounding);
}
}
protected Color brushColor;
public Color FillBrushColor {
get {
return brushColor;
}
set {
brushColor = value;
}
}
public override void Draw(Graphics g) {
Fill(g);
base.Draw(g);
}
}
以下是 Visual Basic .NET 中 DFilledRectangle 類的代碼。
Visual Basic .NET
Public Class DFilledRectangle
Inherits DHollowRectangle
Implements IFillable
Public Sub New(ByVal rect As Rectangle, _
ByVal penColor As Color, ByVal brushColor As Color)
MyBase.New(rect, penColor)
Me.brushColor = brushColor
End Sub
Public Sub Fill(ByVal g As Graphics) Implements IFillable.Fill
Dim b = New SolidBrush(FillBrushColor)
Try
g.FillRectangle(b, bounding)
Finally
b.dispose()
End Try
End Sub
Protected brushColor As Color
Public Property FillBrushColor() As Color _
Implements IFillable.FillBrushColor
Get
Return brushColor
End Get
Set(ByVal Value As Color)
brushColor = Value
End Set
End Property
Public Overrides Sub Draw(ByVal g As Graphics)
Dim p = New Pen(penColor)
Try
Fill(g)
MyBase.Draw(g)
Finally
p.Dispose()
End Try
End Sub
End Class