一个方法是在一个意想不到的时间被叫 [英] A method was called at an unexpected time
问题描述
我试图使用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()
方法不再存在。
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();
}
推荐答案
你需要等待异步方法来完成。所以你可以使用新的等待作为一个选项:
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.
这篇关于一个方法是在一个意想不到的时间被叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!