如果不调用dispose()会发生什么? [英] What happens if i don't call dispose()?

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

问题描述

    public void screenShot(string path)
    {
        var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                                        Screen.PrimaryScreen.Bounds.Height,
                                        PixelFormat.Format32bppArgb);

        var gfxScreenshot = Graphics.FromImage(bmpScreenshot);
        gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
                                    Screen.PrimaryScreen.Bounds.Y,
                                    0,
                                    0,
                                    Screen.PrimaryScreen.Bounds.Size,
                                    CopyPixelOperation.SourceCopy);

        bmpScreenshot.Save(path, ImageFormat.Png);
    }

我正在使用此代码捕获计算机的屏幕.

I was using this code to capture my computer's screen.

但是今天我发现有一个名为Bitmap.Dispose()的方法.

But today I found out that there was a method called Bitmap.Dispose().

是否调用Dispose()有什么区别?代码运行至关重要吗?

What is the difference between when Dispose() is called or not? Is it crucial for the code to run?

推荐答案

如果类型实现了IDisposable接口,则一定要调用Dispose方法(显式地或通过using块).

If a type implements the IDisposable interface, you should definitely call the Dispose method (either explicitly or by a using block).

如果我不打电话给dispose()会怎样?

What happens if i don't call dispose()?

如果不这样做,则析构函数(finalizer)负责释放资源.但是,它有一些缺点:

If you don't do so, the destructor (finalizer) is responsible for freeing the resources; however, it has some drawbacks:

  • 不是确定性的:终结器由GC在专用线程上执行. GC决定何时运行它们.如果保留了对对象的引用(例如,在主应用程序窗口中),则终结处理程序可能要等到您退出应用程序后才能执行.
  • 开销:除非终结器被抑制,否则GC有一些要破坏的对象要做.
  • 危险:如果终结器抛出异常,则它被认为是致命的,将使整个应用程序崩溃.

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

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