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

前端 未结 4 1504
别那么骄傲
别那么骄傲 2021-01-11 17:44
    public void screenShot(string path)
    {
        var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                                        Scree         


        
4条回答
  •  情深已故
    2021-01-11 18:24

    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.

提交回复
热议问题