如果我不调用Dispose画笔对象上会发生什么

如果我不调用Dispose画笔对象上会发生什么

本文介绍了如果我不调用Dispose画笔对象上会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我不叫的Dispose 对象在这个code片段会发生什么?

 私人无效panel_Paint(对象发件人,PaintEventArgs的E)
{
    VAR笔=笔(Color.White,1);
    //做一些图纸
}


解决方案

将由GC在未来某个不确定的点进行收集,您是否叫的Dispose

然而,通过笔(例如,GDI +手柄)持有的任何非托管资源不会被通过GC进行清理。在GC只清理托管资源。调用 Pen.Dispose ,您可以确保这些非托管资源的及时和您没有泄漏资源清理。

现在,如果有一个终结,而且终结清理非托管资源那么那些说非托管资源将被清理时,是垃圾收集。但问题是:


  1. 您应该叫的Dispose 明确,让你释放你的非托管资源,和

  2. 您应该不需要担心的,如果有一个终结的实施细节,并清理非托管资源。

工具的IDisposable 的IDisposable 是处置非托管资源。这是在.NET中的格局。

有关此主题的previous意见,请参阅该answer.

What happens if I don't call Dispose on the pen object in this code snippet?

private void panel_Paint(object sender, PaintEventArgs e)
{
    var pen = Pen(Color.White, 1);
    //Do some drawing
}
解决方案

The Pen will be collected by the GC at some indeterminate point in the future, whether or not you call Dispose.

However, any unmanaged resources held by the pen (e.g., a GDI+ handle) will not be cleaned up by the GC. The GC only cleans up managed resources. Calling Pen.Dispose allows you to ensure that these unmanaged resources are cleaned up in a timely manner and that you aren't leaking resources.

Now, if the Pen has a finalizer and that finalizer cleans up the unmanaged resources then those said unmanaged resources will be cleaned up when the Pen is garbage collected. But the point is that:

  1. You should call Dispose explicitly so that you release your unmanaged resources, and
  2. You shouldn't need to worry about the implementation detail of if there is a finalizer and it cleans up the unmanaged resources.

Pen implements IDisposable. IDisposable is for disposing unmanaged resources. This is the pattern in .NET.

For previous comments on the this topic, please see this answer.

这篇关于如果我不调用Dispose画笔对象上会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:44