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

我的未来我决定 提交于 2019-12-01 05:56:49

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

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

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

  • Is not deterministic: finalizers are executed by the GC on a dedicated thread. The GC decides when to run them. If a reference is kept to the object (eg. in main app window), it is possible that the finalizer will not be executed until you exit the application.
  • Overhead: unless the finalizer is suppressed, the GC has some todo with the objects to destroy.
  • Dangerous: if a finalizer throws an exception, it is considered fatal and will crash the whole application.

It is mandatory to call Dispose. If you don't, there are unmanaged resources such as GDI objects that won't be cleaned up. Which means you're gonna have memory leaks.

So yes, do call Dispose (or better, use using (...) { ... }).

Basically your code should look like this

public void screenShot(string path)
{
    using (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);
    }
}

This ensures the unmanaged resources used by the bitmap object are properly released. With one single bitmap you won't run really into trouble if not disposing properly, but once you start bulk processing it becomes critical. Not disposing properly will cause out of memory issues, I've seen memory filling up really fast with improper coding.

The "Dispose" method comes from the "IDisposable" interface and does the following:

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

Basically you can say that the resources used are not released immediately . Not even when they are no longer needed. But only when the garbage collector releases them.

For more information check out the MSDN: IDisposable Interface

Other useful links on this topic:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!