如果我不在 pen 对象上调用 Dispose 会发生什么? [英] What happens if I don't call Dispose on the pen object?

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

问题描述

如果我不在此代码片段中的 pen 对象上调用 Dispose 会发生什么?

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
}

推荐答案

Pen 将在未来的某个不确定点被 GC 收集,无论您是否调用 Dispose.

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

然而,任何由笔持有的非托管资源(例如,GDI+ 句柄)都不会被 GC 清除.GC 只清理托管资源.调用 Pen.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.

现在,如果 Pen 有一个终结器,并且该终结器清除了非托管资源,那么当 Pen 被垃圾回收时,这些非托管资源将被清除.但重点是:

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. 您应该显式调用 Dispose 以便释放您的非托管资源,并且
  2. 您无需担心是否有终结器以及它会清理非托管资源的实现细节.
  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 实现了 IDisposable.IDisposable 用于处理非托管资源.这是 .NET 中的模式.

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.

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

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