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 was using this code to capture my computer's screen.
But today I found out that there was a method called Bitmap.Dispose().
What is the difference between when Dispose() is called or not? Is it crucial for the code to run?
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:
- Garbage Collection
- using Statement (C# Reference)