[英]Background task in UWP
I want to use a background task for my UWP app. 我想为我的UWP应用使用后台任务。
The below code, is my back button click event in windows mobile: 下面的代码是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? 我究竟做错了什么?
Your background task is exiting before the DispatcherTimer gets a chance to ever execute, because you mark the Deferral as complete. 因为将Deferral标记为完成,所以在DispatcherTimer有机会执行之前,您的后台任务正在退出。 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). 在完成后台任务中的所有工作(或直到您从系统收到TaskCanceled事件)之前,您应该保留Deferral。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.