具有时间触发错误的WinRT后台任务

时间:2015-02-17 10:50:32

标签: c# windows-runtime background-process sqlite-net winrt-component

我已将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);
 }

后台任务成功触发,数据仅在第一次运行时保存到SQLite DB myRepository.Save(entity);表。 我得出了这个结论,因为我记录了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);方法。为什么要这样做?

1 个答案:

答案 0 :(得分:0)

如果系统使用了太多资源,系统可能会终止您的后台任务。锁屏应用程序每15分钟只有2秒的CPU时间。您可以在此处获取更多详细信息:https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977056.aspx

您还可以使用BackgroundTaskCompletedEventArgs中的CheckResult()方法了解后台任务被暂停的原因。

在任务完成事件处理程序中,您可以执行以下操作:

private async void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
{
    try
    {
        args.CheckResult();
    }
    catch(Exception e)
    {
        // add a log/breakpoint here
    }
}

至少应该让你对出现问题的方法有所了解。