gpt4 book ai didi

c# - 如果我不调用 dispose() 会发生什么?

转载 作者:太空狗 更新时间:2023-10-29 22:11:56 43 4
gpt4 key购买 nike

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

我正在使用这段代码来捕获我的计算机屏幕。

但是今天我发现有一个方法叫做Bitmap.Dispose()。

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

最佳答案

如果一个类型实现了 IDisposable 接口(interface),您绝对应该调用 Dispose 方法(明确地或通过 using block )。

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

如果不这样做,析构函数(finalizer)负责释放资源;然而,它也有一些缺点:

  • 不是确定性的:终结器由 GC 在专用线程上执行。 GC 决定何时运行它们。如果保留对对象的引用(例如,在主应用程序窗口中),则可能在您退出应用程序之前不会执行终结器。
  • 开销:除非终结器被抑制,否则 GC 与要销毁的对象有一些关系。
  • 危险:如果终结器抛出异常,则它被认为是致命的并且会导致整个应用程序崩溃。

关于c# - 如果我不调用 dispose() 会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32397248/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com