I'm building a UWP app that gets a list of files from a folder, do some processing on them, then get rid of the files.
This was working fine:
List<StorageFile> files;
public MainPage()
{
this.InitializeComponent();
files = new List<StorageFile>();
}
private async Task<List<StorageFile>> GetFiles(StorageFolder folder)
{
var items = await folder.GetItemsAsync();
foreach (var item in items)
{
if (item.GetType() == typeof(StorageFile))
files.Add(item);
else
await GetFiles(item as StorageFolder);
}
return files;
}
private async void GetFilesBtn_Click(object sender, RoutedEventArgs e)
{
// opening folder picker, then selecting a folder
var files = await GetFiles(folder);
// process files
ProcessFiles(files);
// dispose
DisposeFiles(files);
}
However, when working with large number of files, the memory consumption went really high (obviously).
So what came to mind is to use yield return file
and process each file as it came, then once I'm done with that file I can dispose of it, and start working on the next file and so on.
What I've tried to do is this:
public async Task<IEnumerable<StorageFile>> GetFiles(StorageFolder folder)
{
var items = await folder.GetItemsAsync();
foreach (var item in items)
{
if (item.GetType() == typeof(StorageFile))
yield return item;
else
await GetFiles(item as StorageFolder);
}
}
Then:
foreach (var file in GetFiles(folder))
{
// process file
ProcessFile(file);
// dispose
DisposeFile(file);
}
When doing this I'm getting:
The body of 'GetFiles(StorageFolder)' cannot be an iterator block because Task IEnumerable StorageFile is not an iterator interface type.
I've never used yield return
before so I'm not sure how to accomplish this.