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?

2 Answers 2

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

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

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.