1

我有一个简单的 Metro 风格应用程序,它给我一个(异步和等待)问题。

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()
}

问题是文件名列表被过早访问 - 在它完全加载项目之前。
这是因为 async 方法 - 程序继续执行下一行代码,而 async 方法继续其处理。

完全加载后如何访问列表(在异步方法完成后)?

有没有办法在 Metro 应用程序中不使用异步来完成我想要做的事情?

4

1 回答 1

3

您也需要调用方法是异步的 - 而不是有一个变量fileNames,我会让LoadList方法返回它。所以你会有:

public async Task ProcessFiles()
{
    List<string> fileNames = await LoadList();
    // Now process the files
}

public async Task<List<string>> LoadList()
{
    List<string> fileNames = new List<string>();
    // Do stuff...
    return fileNames;
}

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 BlockingCollection of some kind. EDIT: As Stephen points out, TPL Dataflow would be a great fit here too.

于 2012-09-28T22:22:23.850 回答