1

我想创建获取 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();

如何解决这个问题?

4

2 回答 2

5

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 的方法应该利用 await:

var pic = new PictureManager();
List<string> images = await pic.GetImages();;
bool hasValue = images.Count > 0;
Debug.WriteLine(string.Format("Has value {0}", hasValue));
于 2012-09-26T16:32:44.957 回答
0

我相信你应该从 Completed 处理程序中调用 GetResults,而不是立即调用 GetItemsAsync() 的结果。

于 2012-09-26T16:35:03.660 回答