public void screenShot(string path)
{
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Scree
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:
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 (...) { ... }
).
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:
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.