谁能告诉我如何最好地处理内存流?以前,我有这个,一切正常:
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;
Run Code Online (Sandbox Code Playgroud)
我后来才意识到,由于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;
}
Run Code Online (Sandbox Code Playgroud)
问题出在这行代码中:
myBitmapImage.StreamSource = strmImg;
Run Code Online (Sandbox Code Playgroud)
我的假设是这是引用内存位置,并且dispose显然清理了该位置,并且它在过去工作,因为它从未正确处理过
我的问题是,如何使用MemoryStream并在使用后正确处理,同时仍然保留我需要的转换数据(图像)?
谢谢,
ROKA
你需要添加这一行:
myBitmapImage.CacheOption = BitmapCacheOption.OnLoad;
Run Code Online (Sandbox Code Playgroud)
在加载时将整个映像缓存到内存中.如果没有此行,则CacheOption属性的默认值OnDemand将保留对流的访问权,直到需要映像为止.所以你的代码应该是:
using(MemoryStream strmImg = new MemoryStream(profileImage.Image))
{
BitmapImage myBitmapImage = new BitmapImage();
myBitmapImage.BeginInit();
myBitmapImage.CacheOption = BitmapCacheOption.OnLoad;
myBitmapImage.StreamSource = strmImg;
myBitmapImage.DecodePixelWidth = 200;
myBitmapImage.DecodePixelWidth = 250;
myBitmapImage.EndInit();
this.DemographicInformation.EmployeeProfileImage = myBitmapImage;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
861 次 |
| 最近记录: |