How to free image cache/memory in Windows Phone 8?

2020-08-01 06:03发布

问题:

In my Windows Phone 8 application I have a page with a LongListSelector which is bound to a list of 1000 objects having a property for base64string for image. Now to display the image, I wrote this converter to convert the bas64string into a stream.

public object Convert(object value, Type targetType, object parameter,  System.Globalization.CultureInfo culture)
{
    if (!value.ToString().Contains("http://"))
    {
        string str = value.ToString();
        byte[] bytes = Converter.FromBase64String(str);

        using (MemoryStream stream = new MemoryStream(bytes))
        {
            stream.Seek(0, SeekOrigin.Begin);

            BitmapImage image = new BitmapImage();
            image.SetSource(stream); 
            bytes = null;
            var memoryusage = string.Format("Memory: {0} bytes", 
            DeviceExtendedProperties.GetValue("ApplicationCurrentMemoryUsage"));
            Debug.WriteLine(memoryusage);
            return image;
        }
    }
    else
    { 
        return null;
    }
}

And this is the memoryusage:

    Memory: 92549120 bytes
    Memory: 92946432 bytes
    Memory: 92946432 bytes
    Memory: 92946432 bytes
    Memory: 92946432 bytes
    Memory: 93192192 bytes
    Memory: 93192192 bytes
    Memory: 96079872 bytes
    Memory: 100700160 bytes
    Memory: 100700160 bytes
    Memory: 109568000 bytes
    Memory: 111734784 bytes
    Memory: 142852096 bytes
    Memory: 143056896 bytes
    Memory: 143056896 bytes
    Memory: 143261696 bytes
    Memory: 140791808 bytes
    Memory: 141103104 bytes
    Memory: 141529088 bytes
    Memory: 142151680 bytes
    Memory: 146784256 bytes
    Memory: 146784256 bytes
    Memory: 155066368 bytes
    Memory: 156368896 bytes

At memory equals to or maybe some bytes greater than this 156368896 bytes, the application crashes with the EngineExecutionException. Once I got "OutOfMemoryException for this:

image.SetSource(stream);

Obviously this is a memory issue. I need to clear image cache memory but how? I see the link in this answer https://stackoverflow.com/a/12267163/1949475, but I'm unable to use it.

Note: not all images are displayed at the same time, and the application takes this much memory after I go back and come back to the page again changing the data to be displayed in the LongListSelector.

回答1:

It is important to set in your converter class

BitmapImage image = new BitmapImage(); 
image.DecodePixelType = DecodePixelType.Logical; 
image.CreateOptions = BitmapCreateOptions.BackgroundCreation; 
image.CreateOptions = BitmapCreateOptions.DelayCreation; 
image.DecodePixelWidth = 56; 
image.DecodePixelHeight = 100;