UWP 中的后台任务 [英] Background task in UWP

查看:27
本文介绍了UWP 中的后台任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的 UWP 应用使用后台任务.

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

下面的代码,是我在 windows mobile 中的后退按钮点击事件:

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?

推荐答案

您的后台任务在 DispatcherTimer 有机会执行之前退出,因为您将延迟标记为已完成.您应该保持延迟,直到后台任务中的所有工作都完成(或直到您从系统收到 TaskCanceled 事件).

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

这篇关于UWP 中的后台任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆