I want to get all images from a storage folder in background task. Firstly registered a background task in app_entering background method. I am also able to debug Run method,but
You have an issue here:
var differal = taskInstance.GetDeferral();
UpdateUI();
differal.Complete();
UpdateUI
is an async method, so the method call will end immediately (while the method continues executing in the background). Therefore, you're calling differal.Complete();
before the end of the work.
A simple way to solve that is to pass the deferral as parameter to the UpdateUI
method, and complete it at the end:
public async void UpdateUI(BackgroundTaskDeferral deferral)
{
StorageFolder folder = await KnownFolders.PicturesLibrary.GetFolderAsync("Wall_e_photos")//here execution stops and backgroundtaskhost exits.
var files = await GetFilesAsync();
foreach (StorageFile file in files)
{
if (file.Name.Contains("wall_e"))
{
}
}
deferral.Complete();
}
An alternative is to change UpdateUI
to be async Task
, then wait for its continuation:
public async void Run(IBackgroundTaskInstance taskInstance)
{
var differal = taskInstance.GetDeferral();
await UpdateUI();
differal.Complete();
}
public async Task UpdateUI()
{
...
}