Setting a wallpaper in background task

前端 未结 1 1237
隐瞒了意图╮
隐瞒了意图╮ 2021-01-26 06:32

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

相关标签:
1条回答
  • 2021-01-26 07:11

    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()
    {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题