簡體   English   中英

位圖圖像處理時內存不足異常

[英]Outofmemory exception when do bitmapimage dispose

我創建了WPF Windows應用程序以使用網格顯示更多圖像。 我的以下代碼在運行application.exe時出現OutOfMemory Exception

byte[] buffer = File.ReadAllBytes(path);
File.Delete(path);
if (buffer == null)
   return null;
using (MemoryStream mStream = new MemoryStream(buffer))
{             
   BitmapImage bi = new BitmapImage();
   bi.BeginInit();
   bi.CacheOption = BitmapCacheOption.OnLoad;

   bi.StreamSource = mStream;
   bi.EndInit();              
   bitmap = bi;
   bitmap.Freeze();
   mStream.Close();
   mStream.Dispose();
}

我從stackoverflow找到了一些解決方案,並如下更改了我的編碼,

BitmapImage image = new BitmapImage();
{
    image.BeginInit();
    // image.CreateOptions = BitmapCreateOptions.n;
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.UriSource = new Uri(path);
    image.EndInit();
    File.Delete(path);
    bitmap = image;
    image.UriSource = null;
    image = null;
}

但是此代碼image used by another process而異常,或者cant open from locked fileimage used by another process

我完全感到困惑,為什么我的應用程序經常由OutOfMemory引起或used by another process異常使用?

從評論中可以看出,您做錯了什么。 您正在初始化對象類型BitmapImage並立即將其聲明為null。 因此,您事先聲明的所有內容都變得毫無用處。

您應該在此處利用using()語句功能。 如果代碼保留了該語句,則GarbageCollector將自動接管並為您處置所有內容:

using(BitmapImage image = new BitmapImage())
{
    image.BeginInit();
    // image.CreateOptions = BitmapCreateOptions.n;
    image.CacheOption = BitmapCacheOption.OnLoad;
    image.UriSource = new Uri(path);
    image.EndInit();
    bitmap = image.Clone();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM