Search code examples
c#uwpbackground-task

Infinite background task UWP


I need to implement the functionality of scheduled recording of a live media stream. One of the conditions is that the application does not have to be running. (It should be running in the background) I have a method StartSchedulerAsync that, when started, infinitely checks whether it is necessary to start recording. So, I need to run this method in the background task (when the PC starts, and when the program first starts), and so that it runs in the background for an infinite amount of time. I have read about ExtendedExecutionSession, but as I understand it does not work when the computer starts and in the background.

I tried it, it works well, but only when the program is open.

private async Task RequestExtendedExecution()
        {
            var newSession = new ExtendedExecutionSession
            {
                Reason = ExtendedExecutionReason.Unspecified,
                Description = "Long Running Radio Recorder"
            };
            var result = await newSession.RequestExtensionAsync();
            switch (result)
            {
                case ExtendedExecutionResult.Allowed:
                    Task.Run(async () => await BackgroundRecordingService.StartSchedulerAsync());
                    break;

                default:
                case ExtendedExecutionResult.Denied:
                    break;
            }
        }

Solution

  • By default, Background tasks may generally run for a maximum of twenty-five seconds before they are cancelled.

    But you can use extendedBackgroundTaskTime restricted capability to prevent background tasks from being cancelled or terminated due to execution time limits. You can refer to the official documentation Run background tasks indefinitely, add extendedBackgroundTaskTime capability in Package.appxmanifest.

    <Package
        ... 
        xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
        IgnorableNamespaces="uap mp rescap">
    ...
      <Capabilities>
        <rescap:Capability Name="extendedBackgroundTaskTime"/>
      </Capabilities>
    </Package>