问题
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 none of the await methods are working-
public void Run(IBackgroundTaskInstance taskInstance)
{
var differal = taskInstance.GetDeferral();
UpdateUI();
differal.Complete();
}
public async void UpdateUI()
{
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"))
{
}
}
}
Struggling from long time..Initially background tasks was not working,after it started working..now storage folder issue (backgroundtask exits when getting the folder).
Also for a note I followed this link- http://www.codeguru.com/win_mobile/win_store_apps/setting-wallpapers-in-a-windows-8-store-app-with-vb.htm
There they have used dispatcher,If I use var dispatcher=MyDispatcher = GetForCurrentThread().Dispatcher,then It gives null reference exception
IF I use Windows.ApplicationModel.Core.CoreApplication.MainView ,then it gives could not create a new view exception..
Please help me...
回答1:
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()
{
...
}
来源:https://stackoverflow.com/questions/44605481/setting-a-wallpaper-in-background-task