WinRT C# - 内存不足 - 读取图像文件

时间:2014-09-17 17:52:09

标签: c# windows-runtime bitmapimage

我有一个相当简单的程序,试图读取我的图片库中的所有图形文件。我为每个文件创建一个bitmapImage,我从不使用它或引用它。在阅读了61个文件之后,我得到了一个Out of Memory异常 - 它是可重现的,它总是在第61个文件上死掉。

BitmapImage bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
Windows.Storage.Streams.IRandomAccessStream fileStream =
      await pic.OpenAsync(Windows.Storage.FileAccessMode.Read);
      await bitmapImage.SetSourceAsync(fileStream);

上面的代码片段显示了我正在做的事情的要点。我在方法中创建了一个bitmapImage,将它返回给调用者,从不保留它或引用它。

鉴于我没有提及bitmapImages,不应该GC收集未引用的位图吗?

非常感谢任何帮助或指示。

谢谢,

-----这是扩展代码------

    private IEnumerator<StorageFile> hdEnum = null;

    /*
     * Initialize to read all the pic files in the PicturesLibary.
     * 
     */

    private async Task initializeEnum()
    {
        if (hdEnum != null)
        {
            // I have already been initialised so go away
            return;
        }

        folder = Windows.Storage.KnownFolders.PicturesLibrary;

        // Set query options with filter and sort order for results
        List<string> fileTypeFilter = new List<string>();
        fileTypeFilter.Add(".jpg");
        fileTypeFilter.Add(".png");
        fileTypeFilter.Add(".bmp");
        fileTypeFilter.Add(".gif");
        var queryOptions = new QueryOptions(CommonFileQuery.OrderByName, fileTypeFilter);

        // Create query and retrieve files
        var query = folder.CreateFileQueryWithOptions(queryOptions);

        // Query the folder.
        var fileList = await query.GetFilesAsync();
        hdEnum = fileList.GetEnumerator();
    }

    /*
     * Read and return the next picture file in the PicturesLibrary
     */

    public async Task<BitmapImage> next()
    {
        BitmapImage bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage(); ;

        StorageFile pic = null;

        if (hdEnum == null)
        {
            await initializeEnum();
        }

        if (hdEnum.MoveNext())
        {
            pic = hdEnum.Current;   // hdEnum is an enumerator on the list of image files
        }           

        if (pic != null)
        {
            // come here if I have an image to read
            String path = pic.Path;


            Windows.Storage.Streams.IRandomAccessStream fileStream =
            await pic.OpenAsync(Windows.Storage.FileAccessMode.Read);
            await bitmapImage.SetSourceAsync(fileStream);
            fileStream.Dispose();

            // force a GC - this makes no difference, it still dies after the 61st file
            GC.Collect();
            Debug.WriteLine("Read: " + ++fileCount + " " + pic.Path + " " + GC.GetTotalMemory(true));
        }

         bitmapImage = null;  // EXPLICITLY MAKING IT NULL - no references
        return (bitmapImage);
    }

0 个答案:

没有答案