后台任务延迟。完成

Mic*_*art 3 c# microsoft-metro

我的问题是,这个deferral.complete()方法到底是什么,这个方法是调用 event task.Compledet,还是有办法从BackgroundTaskSyncer我的类中调用一个方法BackgroundSyncer????当我运行程序时,我会从 BackgroundTaskSyncer 执行 Run 方法,但在其他类中什么都不做??

    namespace NotificationTask
            {
                public sealed class BackgroundTaskSyncer : IBackgroundTask
                {
                    public void Run(IBackgroundTaskInstance taskInstance)
                    {
                        BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
                        deferral.Complete();
                    }
                }
                }
    namespace Services
    {

    public static class BackgroundSync
        {
    private static async Task RegisterBackgroundTask()
            {
                try
                {
                    BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();
                    if (status == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity || status == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity)
                    {
                        bool isRegistered = BackgroundTaskRegistration.AllTasks.Any(x => x.Value.Name == "Notification task");
                        if (!isRegistered)
                        {
                            BackgroundTaskBuilder builder = new BackgroundTaskBuilder
                            {
                                Name = "Notification task",
                                TaskEntryPoint =
                                    "NotificationTask.BackgroundTaskSyncer"
                            };
                            builder.SetTrigger(new TimeTrigger(15, false));
                            builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
                            BackgroundTaskRegistration task = builder.Register();
                            task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
                            task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("The access has already been granted");
                }
            }
    private static void OnCompleted(IBackgroundTaskRegistration task, BackgroundTaskCompletedEventArgs args)
            {
                ToTheBackGroundWork();
            }
Run Code Online (Sandbox Code Playgroud)

Ste*_*ary 6

创建延迟是为了解决async void事件和方法的问题。例如,如果您必须await在后台操作期间这样做,您将使用一个async void Run方法。但问题在于运行时不知道您实际上有更多的工作要做。

因此,延迟是一个对象,您可以使用它来通知运行时“我现在真的完成了”。只有在您需要时才需要延期await

我有一篇博文详细介绍了“异步事件处理程序”和延迟