我正在尝试使用 GetFilesAsync 迭代目录中的所有文件,但每次我调用 GetResults 方法时,它都会抛出一个异常
I'm trying to iterate all files in a directory using GetFilesAsync, but every time I call the GetResults method, it throws an exception that says
System.InvalidOperationException:意外调用了一个方法时间
System.InvalidOperationException: A method was called at an unexpected time
代码很简单
var files = myStorageFolder.GetFilesAsync(); //runs fine
var results = files.GetResults(); //throws the exception
我是 Win 8 开发新手,所以我可能会遗漏一些明显的东西.
I'm new to Win 8 dev so I might be missing something obvious.
编辑(已解决)我正在运行我的控制台应用程序,但现在程序异步运行,files.GetResult()
方法不再存在.
Edit (solved)
I'm running my console application, but now that the program runs async, the files.GetResult()
method no longer exists.
static void Main(string[] args)
{
var files = GetFiles(myStorageFolder);
var results = files.GetAwaiter().GetResults();//Need to add GetAwaiter()
}
static async Task GetFiles(StorageFolder sf)
{
await sf.GetFilesAsync();
}
需要等待异步方法完成.所以你可以使用新的 await 作为一种选择:
You need to wait for the async method to complete. So you could use the new await as one option:
var files = await myStorageFolder.GetFilesAsync();
您可能需要查看有关处理异步方法的文档这里.
You might want to check the documentation on dealing with async methods here.