我編寫了一個代碼來將圖像加載到<image>
控件中,並且由於我需要編輯和保存在多個位置使用的相同圖像,我的位置是修改代碼避免Access violation error
。現在我得到Out of memory exception
。加載圖像時發生內存泄漏C#
private BitmapSource LoadImage(string path)
{
lock (_syncRoot) //lock the object so it doesn't get executed more than once at a time.
{
BitmapDecoder decoder = null;
try
{
//If the image is not found in the folder, then show the image not found.
if (!File.Exists(path) && (path != null))
{
using (var stream = new System.IO.MemoryStream())
{
if (!File.Exists(Path.GetTempPath() + "ImageNotFound.jpg"))
{
System.Drawing.Bitmap ss = Ashley.ProductData.MarketSeries.Presentation.Properties.Resources.ImageNotFound;
using (FileStream file = new FileStream(Path.GetTempPath() + "ImageNotFound.jpg", FileMode.Create, FileAccess.Write))
{
ss.Save(stream, ImageFormat.Jpeg);
stream.Position = 0;
stream.WriteTo(file);
}
}
}
path = Path.Combine(Path.GetTempPath(), "ImageNotFound.jpg");
NoImage = false;
}
else
{
if (!EnableForEdit)
NoImage = false;
else
NoImage = true;
}
if (!string.IsNullOrEmpty(path) && (!NoImage || File.Exists(path)))
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
return decoder.Frames.FirstOrDefault();
}
}
else
return null;
}
catch (OutOfMemoryException ex)
{
MessageBox.Show("Insufficient memory to handle the process. Please try again later.", "Application alert");
return null;
}
catch (Exception ex)
{
// Error handling.
ShowMessages.AlertBox(ex.Message, MethodInfo.GetCurrentMethod().Name);
throw ex;
}
finally
{
decoder = null;
}
}
}
我需要知道,如果在上面的代碼中的任何內存泄漏或有沒有更好的方式來加載符合我的要求,這圖像。
需要一些時間來檢查這是否工作。謝謝 – John