2014-06-30 41 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