Setting a wallpaper in background task

一笑奈何 提交于 2019-12-02 11:31:37

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()
{
    ...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!