How to Disable UWP App Suspension?

前端 未结 5 561
滥情空心
滥情空心 2021-01-18 22:03

I am using C# to develop a UWP app for Windows 10 running only on desktop computers, targeting platform version 10.0.14393.0. Due to business requirements, the app lifecycle

5条回答
  •  耶瑟儿~
    2021-01-18 22:13

    According to this article in MSDN magazine you can also use background tasks to keep the application alive. The article claims that background tasks should be preferred over the Extended Session method.

    A BackgroundTask Implementation

    public sealed class TimerTask : IBackgroundTask
    {
      public void Run(IBackgroundTaskInstance taskInstance)
      {
        var deferral = taskInstance.GetDeferral();
        taskInstance.Canceled += TaskInstance_Canceled;
        await ShowToastAsync("Hello from Background Task");
        deferral.Complete();
      }
      private void TaskInstance_Canceled(IBackgroundTaskInstance sender,
        BackgroundTaskCancellationReason reason)
      {
        // Handle cancellation
        deferral.Complete();
      }
    }
    

    In the application manifest, the background task must also be registered. This registration tells Windows the trigger type, the entry point and the executable host of the task, as follows:

    
      
        
          
        
      
    

    Background Task Registration

    private void RegisterBackgroundTasks()
    {
      BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
      builder.Name = "Background Test Class";
      builder.TaskEntryPoint = "BackgroundTaskLibrary.TestClass";
      IBackgroundTrigger trigger = new TimeTrigger(30, true);
      builder.SetTrigger(trigger);
      IBackgroundCondition condition =
        new SystemCondition(SystemConditionType.InternetAvailable);
      builder.AddCondition(condition);
      IBackgroundTaskRegistration task = builder.Register();
      task.Progress += new BackgroundTaskProgressEventHandler(task_Progress);
      task.Completed += new BackgroundTaskCompletedEventHandler(task_Completed);
    }
    

提交回复
热议问题