C# Dispose()释放顺序杂谈

View Code
public void drawWord_first(object sender, PaintEventArgs e) 
{
Graphics gd = e.Graphics;
//g.SmoothingMode = SmoothingMode.AntiAlias;
GraphicsPath stringPath = new GraphicsPath();
charInfo chars=new charInfo();
string drawWords = chars.getChars();
stringPath.AddString(chars.getChars(), new FontFamily("楷体_GB2312"), 0, 96, new Point(0, 0), StringFormat.GenericDefault);
gd.DrawPath(new Pen(Brushes.Blue),stringPath);
gd.Dispose();

}
View Code
public void OnPaint_drawTian(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
this.tianHeight = 200;
this.tianWidth = 200;
this.tianLeftTop = new Point(0,0);
this.tianRightTop = new Point(this.tianWidth,0);
this.tianLeftBottom = new Point(0,this.tianHeight);
this.tianRightBottom = new Point(this.tianWidth,this.tianHeight);
this.tianTopCenter = new Point(this.tianWidth/2,0);
this.tianBottomCenter=new Point(this.tianWidth/2,this.tianHeight);
this.tianLeftCenter = new Point(0,this.tianHeight/2);
this.tianRightCenter = new Point(this.tianWidth,this.tianHeight/2);

this.tianRectangle = new Rectangle(this.tianLeftTop,new Size(this.tianWidth,this.tianHeight));
this.tianPen=new Pen(Brushes.Red,2);
this.tianPen.DashStyle = DashStyle.DashDot;
g.DrawLine(this.tianPen, this.tianRectangle.Left, this.tianRectangle.Top, this.tianRectangle.Left + this.tianWidth, this.tianRectangle.Bottom);
g.DrawLine(this.tianPen,this.tianRightTop,this.tianLeftBottom);
g.DrawLine(this.tianPen,this.tianLeftCenter,this.tianRightCenter);
g.DrawLine(this.tianPen,this.tianTopCenter,this.tianBottomCenter);
this.tianPen.DashStyle = DashStyle.Solid;
g.DrawRectangle(this.tianPen,this.tianRectangle);
//g.Dispose();
}
     

这样释放内存会报 参数无效 异常,经过思索,貌似第一个g对象被释放掉以后,第二个绘制就会成问题,所以正确写法应当如下:

public void OnPaint_drawTian(object sender, PaintEventArgs e){...//g.Dispose();}
public void drawWord_first(object sender, PaintEventArgs e){...g.Dispose();}                
请问大家,这样写对不,两个函数紧挨着被调用(注释掉第一个dispose语句就是了)

另外内存的释放顺序应该与使用的顺序相反...

-------------------------------------------------------------------------------------------------------------------

 

Dispose与Close没有任何关系.它们的共同点是遵循一个相似的约定. 
Dispose的约定是,这个方法将释放该实例所占用的所有资源,销毁自身. 
注意Dispose的约定是释放所有资源并销毁自身,就是说大多数情况下,被Dispose掉的实例都不应该被再次使用. 
如果一个类同时拥有Dispose和Close方法,一般来说,Dispose中都会调用Close方法.

 

 

 

Close   只是关闭而已,没有释放真正的释放资源,可以重新打开 
Dispose   是把对象销毁,将不再存在 

 

Close是停业整顿,Dispose是炸毁;

 

Close是关门,Dispose是破产。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值