Background task in UWP

2019-08-23 10:23发布

问题:

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).