当我使用 Stream 时,UWP 应用程序使用了太多内存

The UWP application use too many memory when I use Stream

我创建了一个应用程序来读取 ZipArchive(100 多张照片),并使用 Stream、MemoryStream、IRandomAccessStream 和 BinaryReader 来设置位图图像的来源。

private byte[] GetBytes(ZipArchiveEntry entity)
    {
        Stream stream = entity.Open();
        MemoryStream ms = new MemoryStream();
        BinaryReader reader = null;
        byte[] imageData = null;
        try
        {
            stream.CopyTo(ms);
            imageData = new byte[ms.Length];
            string fileclass = "";
            reader = new BinaryReader(ms);
            ms.Seek(0, 0);
            imageData = reader.ReadBytes((int)ms.Length);
            //Verify png jpg bmp
            some code and return imageData
            //throw exception,return null
            else
            {
                throw new Exception();
            }
        }
        catch (Exception ex)
        {
            return null;
        }
        //Dispose
    }

BitmapImage.SetSource by byte[]

public async Task<MangaPageEntity> GetImageFromZipArchiveEntry(ZipArchiveEntry entity, int index)
    {
        MangaPageEntity mpe = new MangaPageEntity();
        mpe.Index = index;
        IRandomAccessStream iras = null;
        try
        {
            byte[] data = GetBytes(entity);
            iras = data.AsBuffer().AsStream().AsRandomAccessStream();
            iras.Seek(0);
            await mpe.Picture.SetSourceAsync(iras);
        }//catch and dispose
        return mpe;

这样一来,运行 at phone ..

也太占内存了

尝试将您的流和其他 IDisposable 放入 using statement:

private byte[] GetBytes(ZipArchiveEntry entity)
{
    using (Stream stream = entity.Open())
    using (MemoryStream ms = new MemoryStream())
    {
        byte[] imageData = null;
        try
        {
            stream.CopyTo(ms);
            imageData = new byte[ms.Length];
            string fileclass = "";
            using (BinaryReader reader = new BinaryReader(ms))
            {
                ms.Seek(0, 0);
                imageData = reader.ReadBytes((int)ms.Length);
            }              
            //Verify png jpg bmp some code and return imageData
            //throw exception,return null
            else
            {
                throw new Exception();
            }
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    //Dispose
}

public async Task<MangaPageEntity> GetImageFromZipArchiveEntry(ZipArchiveEntry entity, int index)
{
    MangaPageEntity mpe = new MangaPageEntity();
    mpe.Index = index;
    try
    {
        byte[] data = GetBytes(entity);
        using (IRandomAccessStream iras = data.AsBuffer().AsStream().AsRandomAccessStream())
        {
            iras.Seek(0);
            await mpe.Picture.SetSourceAsync(iras);
        }
    }//catch and dispose
    return mpe;
}

当您的代码离开 using 时,它会调用 Dispose()。阅读更多内容:Uses of “using” in C#, What is the C# Using block and why should I use it? 可能还有更多内容。