我想创建获取 PictureFolder 中文件列表的方法。我创建了这个方法:
public Task<List<string>> GetImages()
{
var task = new Task<List<string>>(() =>
{
var files = new List<string>(5);
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
IReadOnlyList<IStorageItem> itemsList = picturesFolder.GetItemsAsync().GetResults();
foreach(var item in itemsList)
{
if(item is StorageFile)
{
files.Add(item.Name);
}
}
return files;
});
return task;
}
以及我用于测试此方法的代码:
var pic = new PictureManager();
pic.GetImages().RunSynchronously();
List<string> images = pic.GetImages().Result;
bool hasValue = images.Count > 0;
Debug.WriteLine(string.Format("Has value {0}", hasValue));
我得到了这个例外
System.InvalidOperationException was unhandled by user code
HResult=-2147483634
Message=A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)
Source=Windows.Foundation
StackTrace:
at Windows.Foundation.IAsyncOperation`1.GetResults()
at Praktyka.Models.PictureManager.<GetImages>b__0() in d:\Documents\Visual Studio 2012\Projects\Praktyka\Praktyka\Models\PictureManager.cs:line 63
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
InnerException:
在这一行(方法 GetImages)
IReadOnlyList<IStorageItem> itemsList = picturesFolder.GetItemsAsync().GetResults();
如何解决这个问题?