A method was called at an unexpected time

2019-04-03 22:54发布

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: A method was called at an unexpected time

The code is simply

var files = myStorageFolder.GetFilesAsync(); //runs fine
var results = files.GetResults(); //throws the exception

I'm new to Win 8 dev so I might be missing something obvious.

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

3条回答
趁早两清
2楼-- · 2019-04-03 23:32

If you don't want to use the asynckeyword (in my case, the code was inside a property, so asyncwasn't an option), you can use a TaskAwaiter instead, by chaining these two methods:

var folder = Package.Current.InstalledLocation.GetFolderAsync("folderName").GetAwaiter().GetResult();

This won't throw a InvalidOperationException nor cause a deadlock.

查看更多
该账号已被封号
3楼-- · 2019-04-03 23:37

you should await the var files = myStorageFolder.GetFilesAsync(); as the operation might still be running when you get to next instruction var results = files.GetResults(); //throws the exception

var files = await myStorageFolder.GetFilesAsync(); //runs fine
var results = files.GetResults(); //this will run when call above returns
查看更多
女痞
4楼-- · 2019-04-03 23:51

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.

查看更多
登录 后发表回答