What happens if I do not call 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 used this code to capture the screen of my computer.

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

What is the difference between calling Dispose () or not? Is it important to run the code?

+4
source share
4 answers

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

What happens if I do not call dispose ()?

If you do not, the destructor (finalizer) is responsible for freeing resources; however, it has some disadvantages:

  • : GC . GC , . (, ), , .
  • : , GC .
  • : , .
+7

Dispose. , , GDI, . , .

, , Dispose ( , using (...) { ... }).

+2

:

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);
    }
}

, , , . , , , . - , , .

0

"Dispose" "IDisposable" :

, , , .

In principle, you can say that the resources used will not be sent immediately. Even when they are no longer needed. But only when the garbage collector releases them.

For more information, visit MSDN: IDisposable Interface

Other useful links on this topic:

0
source

Source: https://habr.com/ru/post/1605932/


All Articles