我想创建方法来获取 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();
如何解决这个问题?
RunSynchronously 方法在当前线程上启动一个任务。但是,从 GetItemsAsync 返回的任务已经启动,因此您会收到异常。
您需要重构代码以利用 async/await 关键字:
public async Task<List<string>> GetImages()
{
var files = new List<string>();
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
IReadOnlyList<IStorageItem> itemsList = await picturesFolder.GetItemsAsync();
foreach(var item in itemsList)
{
if(item is StorageFile)
{
files.Add(item.Name);
}
}
return files;
}
同样调用 GetImages 的方法应该利用等待:
var pic = new PictureManager();
List<string> images = await pic.GetImages();;
bool hasValue = images.Count > 0;
Debug.WriteLine(string.Format("Has value {0}", hasValue));
我是一名优秀的程序员,十分优秀!