2014-06-30 40 views
1

我創建了WPF windows應用程序,使用網格顯示更多圖像。當我運行我的application.exe時,我的下面的代碼得到OutOfMemory ExceptionOutmamemory異常當bitmapimage配置

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(); 
} 

我發現從計算器一些解決方案,改變了我的代碼如下以下,

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 processcant open from locked file

我完全困惑爲什麼我的應用程序經常由OutOfMemory或used by another process異常引起?

+0

你可以看看波紋管鏈接,提高RAM性能比較http://social.msdn.microsoft.com/Forums/en -US/5a13a184-ef47-423a-89ed-7ca1b8a0aaf8/build-your-own-memory-optimizer-with-c?forum = netfxnetcom – KVK

+0

你也可以看看你的文章並回答這個問題 - 「我的文章格式很好?我想從其他人那裏閱讀這些帖子嗎?「 –

+0

@KVK即使我嘗試鏈接code.its減少內存大小罰款,但即使經常得到相同的異常。 – MMMMS

回答

0

從評論中採取,你做錯了什麼。您正在初始化ob objct ob類型BitmapImage並立即將其聲明爲空。所以你事先聲明的一切都已經落在了垃圾箱裏。

您應該利用這裏的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(); 
} 
+0

是的,而不是此塊(使用(BitmapImage圖像=新的BitmapImage()){.. 。})只有我使用了我已經存在問題的代碼。即使我使用上面的代碼,我也會得到相同的錯誤。 – MMMMS

+0

不,你沒有。您發佈了2個完全不同的代碼片段,第二個將無法工作。這意味着你的錯誤很可能在其他地方。 – Marco

+1

@Serv我會建議添加'.Clone()'''''bitmap = image.Clone();' – WiiMaxx