在ASP.NET Web API控制器中,我想返回一张图片。为了流式传输图像,我需要一个MemoryStream。通常我会将它包装在一个using语句中,以确保它在使用后被正确处理。但是,由于这是异步执行的Task,因此这种方法不起作用:
public class ImagesController : ApiController
{
private HttpContent GetPngBitmap(Stream stream)
{
var pngBitmapEncoder = new PngBitmapEncoder();
pngBitmapEncoder.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
return new StreamContent(stream);
}
// GET api/images
public Task<HttpResponseMessage> Get(string id, string path)
{
//do stuff
return Task.Factory.StartNew(() =>
{
var stream = new MemoryStream(); //as it's asynchronous we can't use a using statement here!
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = GetPngBitmap(stream)
};
response.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
return response;
}
//how can I dispose stream???
});
}
}
GetPngBitmap
的类型在这种情况下很重要。当“png位图”不再引用流时,可以释放该流。 - CaramirielGetPnGBitmap()
方法后,是否需要在流上调用 Dispose?或者使用 try finally 块,在 finally 中调用 Dispose,或者在返回响应之前调用 Dispose。我不明白问题出在哪里?为什么不能使用 using? - Shakti Prakash SinghStreamContent
即可。 - Kiran