有人能告诉我如何最好地处理内存流吗?之前,我有以下代码并且一切正常:
MemoryStream strmImg = new MemoryStream(profileImage.Image);
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.StreamSource = strmImg;
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.DecodePixelWidth = 250;
myBitmapImage.EndInit();
this.DemographicInformation.EmployeeProfileImage = myBitmapImage;
后来我意识到,由于MemoryStream
实现了IDisposable
接口并应该在使用完毕后进行释放,我会遇到内存泄漏问题,因此我采用了以下实现方式:
using(MemoryStream strmImg = new MemoryStream(profileImage.Image))
{
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.StreamSource = strmImg;
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.DecodePixelWidth = 250;
myBitmapImage.EndInit();
this.DemographicInformation.EmployeeProfileImage = myBitmapImage;
}
问题出在这行代码中:
myBitmapImage.StreamSource = strmImg;
我的假设是这个引用的是内存位置,而dispose明显清理了那个位置,过去之所以起作用是因为它从未被正确处理。
我的问题是,我如何在使用MemoryStream
并在使用后正确处理它时,仍然保留所需的转换数据(Image
)?