[英]What happens if i don't 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);
}
我正在使用此代碼捕獲我的計算機屏幕。
但今天我發現有一個名為Bitmap.Dispose()的方法。
什么時候調用Dispose()有什么區別? 代碼運行至關重要嗎?
如果類型實現了IDisposable
接口,則應該明確地調用Dispose
方法(顯式或using
塊)。
如果我不調用dispose()會發生什么?
如果你不這樣做,析構函數(終結器)負責釋放資源; 但是,它有一些缺點:
必須調用Dispose
。 如果不這樣做,則會有非托管資源(如GDI對象)無法清除。 這意味着你將有內存泄漏。
所以,是的,請調用Dispose
(或更好,使用using (...) { ... }
)。
基本上你的代碼應該是這樣的
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);
}
}
這可確保正確釋放位圖對象使用的非托管資源。 如果沒有正確處理,只需一個位圖就不會遇到麻煩,但一旦開始批量處理,它就變得至關重要了。 不正確處理將導致內存不足問題,我發現內存填充速度非常快,編碼不當。
“Dispose”方法來自“IDisposable”界面,並執行以下操作:
執行與釋放,釋放或重置非托管資源相關的應用程序定義的任務。
基本上你可以說使用的資源不會立即釋放。 即使不再需要它們也不行。 但只有當垃圾收集器釋放它們時。
有關更多信息,請查看MSDN: IDisposable接口
關於此主題的其他有用鏈接:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.