简体   繁体   中英

Outofmemory exception when do bitmapimage dispose

I have created WPF windows application for display more images using grid. My below code getting OutOfMemory Exception when I run my application.exe .

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

I found some solution from stackoverflow and changed my coding as following below,

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

But this code getting exception as that image used by another process or cant open from locked file .

I am totally confused why my application often caused by OutOfMemory or used by another process exception?

Taken from the comments, you are doing something wrong. You are initializing an obejct ob type BitmapImage and instantly declare it as null. So everything you have declared beforehand has gone down the crapper.

you should leverage the using() statements functionality here. If the code leaves this statement the GarbageCollector will automatically take over and dispose everything for you:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM