using is a very helpful statement in C#.  Recently, i work on a visual recognizing project, involving a lot of image processing. When processing a video file frame by frame, a serious memory leak came out due to the indisposed image object. To solve this, we could call dispose() method.


image.Dispose();

Or better approach

using(NImage image = NImage.FromBitmap(videoBMP.BMPBinary))
{
	//do stuff
}

With using statement, won’t worry when to call dispose and try/catch block

e.g.

private void execute()
{
	using (Waster w = new Waster())
	{
		w.Throws();
	}
}

class Waster: IDisposable
{
	public void Throws()
	{
		throw new Exception();
	}

	public void Dispose()
	{
		System.Diagnostics.Debug.WriteLine("i am wasted...");
	}
}

“i am wasted” is still printed out

Advertisements