How to retrieve files from KnowFolders in Windows 8?

1

I want to create method for get list of files in PictureFolder. I create this method:

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

and my code for testing this method:

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

I get this exception

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: 

in this line (method GetImages)

 IReadOnlyList<IStorageItem> itemsList = picturesFolder.GetItemsAsync().GetResults();

How to resolve this problem?

c#
windows-8
.net-4.5
async-await
asked on Stack Overflow Sep 26, 2012 by BILL • edited Dec 25, 2016 by Cœur

2 Answers

5

The RunSynchronously method starts a task on the current thread. However, the task returned from GetItemsAsync is already started and therefore you receive an exception.

You need to refactor your code to take advantage of the async/await keywords:

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

Likewise the method calling GetImages should take advantage of await:

var pic = new PictureManager();
List<string> images = await pic.GetImages();;
bool hasValue = images.Count > 0;
Debug.WriteLine(string.Format("Has value {0}", hasValue));
answered on Stack Overflow Sep 26, 2012 by Kasper Holdum • edited Sep 29, 2012 by Kasper Holdum
0

I believe you should call GetResults from Completed handler, not immediately on result of GetItemsAsync().

answered on Stack Overflow Sep 26, 2012 by Alexei Levenkov

User contributions licensed under CC BY-SA 3.0