Background task in UWP

三世轮回 提交于 2019-12-12 04:46:08

问题


I want to use a background task for my UWP app.

The below code, is my back button click event in windows mobile:

private async void MainPage_BackRequested(object sender, BackRequestedEventArgs e)
    {
       var access= await BackgroundExecutionManager.RequestAccessAsync();
        var task = new BackgroundTaskBuilder
        {
            Name="My task",TaskEntryPoint=typeof(backGroundTask.Class1).ToString()
        };
        trigger = new ApplicationTrigger();
        task.SetTrigger(trigger);
        task.Register();
        //var result = await trigger.RequestAsync();
        if (Frame.CanGoBack)
        {
            Frame.GoBack();
            e.Handled = true;
        }
    }


public void Run(IBackgroundTaskInstance taskInstance)
    {
        _deferral = taskInstance.GetDeferral();
        clearData();
        count1 = 0;
        getDownloadedSongs();

        dispatcherTimer1.Tick += DispatcherTimer1_Tick;
        dispatcherTimer1.Interval = new TimeSpan(0, 0, 3);
        dispatcherTimer1.Start();
        _deferral.Complete();



    }
    DispatcherTimer dispatcherTimer1 = new DispatcherTimer();

 private async void DispatcherTimer1_Tick(object sender, object e)
    {

        try
        {
              clearData();




        }
        catch (Exception ex)
        {
        }



    }

But this code is not working, when I click back button. As per expectation background task code should work, but it is not working. What am I doing wrong?


回答1:


Your background task is exiting before the DispatcherTimer gets a chance to ever execute, because you mark the Deferral as complete. You should hold on to the Deferral until all the work in your background task has been completed (or until you receive a TaskCanceled event from the system).



来源:https://stackoverflow.com/questions/44546208/background-task-in-uwp

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