I have a simple Metro style app that’s giving me an issue with (async & await).
List<string> fileNames = new List<string>();
...
...
LoadList();
...
...
(Problem) Code that accesses the elements of the fileNames List
...
...
private async void LoadList()
{
// Code that loops through a directory and adds the
// file names to the fileNames List using GetFilesAsync()
}
The problem is that the fileNames List is accessed prematurely – before it is fully loaded with items.
This is because of the async method – the program continues with the next line of code while the async method continues its processing.
How can I access the List after it is fully loaded (After the async method is done)?
Is there a way to accomplish what I’m trying to do without using async in Metro apps ?
You need the calling method to be asynchronous too – and rather than having a variable of
fileNames, I’d make theLoadListmethod return it. So you’d have:This does mean that you need to wait for all the files to be found before you start processing them; if you want to process them as you find them you’ll need to think about using a
BlockingCollectionof some kind. EDIT: As Stephen points out, TPL Dataflow would be a great fit here too.