我正在尝试将大量图像加载为 GridApp 模板的数据源。我使用递归函数遍历文件夹:
public async void walk(StorageFolder folder)
{
IReadOnlyList<StorageFolder> subDirs = null;
subDirs = await folder.GetFoldersAsync();
foreach (var subDir in subDirs)
{
await SampleDataSource.AddGroupForFolderAsync(subDir.Path);
walk(subDir);
}
}
这是核心功能:
public static async Task<bool> AddGroupForFolderAsync(string folderPath)
{
if (SampleDataSource.GetGroup(folderPath) != null) return false;
StorageFolder fd = await StorageFolder.GetFolderFromPathAsync(folderPath);
IReadOnlyList<StorageFile> fList1 = await fd.GetFilesAsync();
List<StorageFile> fList2 = new List<StorageFile>();
foreach (var file in fList1)
{
string ext = Path.GetExtension(file.Path).ToLower();
if (ext == ".jpg" || ext == ".png" || ext == ".jpeg") fList2.Add(file);
}
if (fList2.Count != 0)
{
var folderGroup = new SampleDataGroup(
uniqueId: folderPath,
title: fd.Path,
subtitle: null,
imagePath: null,
description: "Description goes here");
foreach (var i in fList2)
{
StorageFile fl = await StorageFile.GetFileFromPathAsync(i.Path);
IRandomAccessStream Stream = await fl.OpenAsync(FileAccessMode.Read);
BitmapImage pict = new BitmapImage();
pict.SetSource(Stream);
if (pict != null && folderGroup.Image == null)
{
folderGroup.SetImage(pict);
}
var dataItem = new SampleDataItem(
uniqueId: i.Path,
title: i.Path,
subtitle: null,
imagePath: pict,
description: "Decription goes here",
content: "Content goes here",
@group: folderGroup);
folderGroup.Items.Add(dataItem);
}
AllGroups.Add(folderGroup);
return true;
}
else { return false; }
}
我需要加载大量文件(164 个文件夹和 1300 多个文件,总共 500 MB)。以后这个数额可能会更大。似乎 IRandomAccessStream 将文件加载到 RAM 中。如何直接从 HDD 将图像加载到应用程序?Windows-Store 应用程序可以吗?是否有可能仍然异步进行?
我知道我的代码需要重构。我不是要求重写它。我只需要在这种情况下如何节省内存的建议。