我将我的定义BackgroundTask
如下:
public sealed class BackgroundSynchronization:IBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
//code
//Network Calls
//Updating Local DB (SQLite)
myRepository.Save(entity); // Saves entity in SQLite Table, and Entity has a Current DateTime field too.
deferral.Complete();
}
}
和TaskRegister
类:
public static class BackgroundTaskRegister {
public static BackgroundTaskRegistration RegisterBackgroundTask(string taskEntryPoint,string taskName,IBackgroundTrigger trigger,IBackgroundCondition condition)
{
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
if (cur.Value.Name == taskName)
{
return (BackgroundTaskRegistration)(cur.Value);
}
}
var builder = new BackgroundTaskBuilder();
builder.Name = taskName;
builder.TaskEntryPoint = taskEntryPoint;
builder.SetTrigger(trigger);
if (condition != null)
{
builder.AddCondition(condition);
}
BackgroundTaskRegistration task = builder.Register();
return task;
}
}
我已在我的应用程序中将触发器注册为:
TimeTrigger myTrigger = new TimeTrigger(15, false);
await BackgroundExecutionManager.RequestAccessAsync();
string entryPoint = "BackgroundTask.BackgroundSynchronization";
string taskName = "Example per 15 minute background task";
BackgroundTaskRegistration tsk = BackgroundTaskRegister.RegisterBackgroundTask(entryPoint, taskName, myTrigger, null);
tsk.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
我的应用程序中也有一个OnComplete
方法:
private async void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
{
var settings = ApplicationData.Current.LocalSettings;
var message = settings.Values["backgroundSyncStatus"].ToString();
var folder = ApplicationData.Current.LocalFolder;
StorageFile file;
var x = await File.DoesFileExistInLocalAsync("BackgroundTaskSucceedLog.txt");
if (!x)
file = await folder.CreateFileAsync("BackgroundTaskSucceedLog.txt");
else
file = await ApplicationData.Current.LocalFolder.GetFileAsync("BackgroundTaskSucceedLog.txt");
await Windows.Storage.FileIO.AppendTextAsync(file, message.ToString() + " " + DateTime.Now.ToString() + Environment.NewLine);
}
后台任务触发成功,数据myRepository.Save(entity);
仅在首次运行时保存到 SQLite DB 表中。当我在OnComplete
方法中记录了条目时,我得出了这个结论。
记录器的结果让我更加困惑。
记录器结果:
2/16/2015 10:51:41 PM <-- Data Saved in SQLite for this entry
2/16/2015 11:07:03 PM
2/16/2015 11:22:26 PM
2/16/2015 11:37:39 PM
2/16/2015 11:52:51 PM
2/17/2015 5:33:00 AM <-- Data Saved in SQLite for this entry
SQLite 中的数据仅保存“一天”的第一个后台任务。我试图调试BackgroundTask
. 第一次运行一切顺利,但在随后的运行中,编译器OnComplete
在到达后直接跳转到方法myRepository.Save(entity);
。为什么要这样做?