The following is a valid code that the stream transmits. If it is enclosed in a using
block, the MemoryStream.Dispose()
method will be called automatically upon return.
public ActionResult CustomChart(int reportID) { Chart chart = new Chart(); using (var imgStream = new MemoryStream()) { chart.SaveImage(imgStream); imgStream.Seek(0, SeekOrigin.Begin); return File(imgStream, "image/png"); } }
You can achieve the same result by placing an object inside a try
block, and then calling Dispose
on the finally block. In fact, according to the MSDN documentation, this is how the using statement is translated by the compiler. And in the try..finally
finally
block will always be executed, even if try
exits via return
.
The compiler will translate the using
block to the following:
MemoryStream imgStream = new MemoryStream(); try { chart.SaveImage(imgStream); imgStream.Seek(0, SeekOrigin.Begin); return File(imgStream, "image/png"); } finally { if (imgStream != null) ((IDisposable)imgStream).Dispose(); }
Dennis traub
source share