How to extend execution of background task in WinUI 3 (analog of ExtendedExecutionSession in UWP)?

2025-02-10T11:59:45.8866667+00:00

My application has a background task that performs a cleanup of unnecessary or unused system files selected by the user. However, this task takes more than 30 seconds to complete, which exceeds the standard time limit.

Question:

Is there any way to increase the execution time of the background task in WinUI 3, similar to ExtendedExecutionSession in UWP?

Additions:

**Current code:

Background task registration in BackgroundTaskProvider class:**

        public IBackgroundTaskRegistration RegisterBackgroundTaskWithSystem(IBackgroundTrigger trigger, Guid entryPointClsid, string taskName)
        {
            foreach (var registrationIterator in BackgroundTaskRegistration.AllTasks)
            {
                if (registrationIterator.Value.Name == taskName)
                {
                    return registrationIterator.Value;
                }
            }
            BackgroundTaskBuilder builder = new BackgroundTaskBuilder();
            builder.Name = taskName;
            builder.SetTaskEntryPointClsid(entryPointClsid);
            builder.SetTrigger(trigger);
            BackgroundTaskRegistration registration;
            try
            {
                registration = builder.Register();
            }
            catch (Exception)
            {
                registration = null;
            }
            return registration;
        }

In App.xaml.cs:

            BackgroundTaskProvider.Instance.RegisterBackgroundTaskWithSystem(new TimeTrigger(15, false), typeof(ScheduledAutoCleanTask).GUID, typeof(ScheduledAutoCleanTask).Name);

Registration of Win32 COM background task in the manifest file:

        <com:Extension Category="windows.comServer">
          <com:ComServer>
            <com:ExeServer Executable="App\App.exe" Arguments="-RegisterProcessAsComServer" DisplayName="App">
              <com:Class Id="3A3DCD6C-3EAB-43DC-BCDE-45671CE800C8" DisplayName="ScheduledAutoCleanTask" />
            </com:ExeServer>
          </com:ComServer>
        </com:Extension>

Current result:
The background task is triggered at the expected time, but terminates before all cleanup operations are completed

Any advice or alternative approaches would be appreciated!

.NET
.NET
Microsoft Technologies based on the .NET software framework.
4,102 questions
Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
822 questions
Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,735 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,289 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jonathan Pereira Castillo 13,820 Reputation points Microsoft Vendor
    2025-02-11T18:58:41.5266667+00:00

    Hi Роман Воскобойников,

    Extending the execution time of background tasks in WinUI 3 can be challenging, especially since WinUI 3 does not directly support ExtendedExecutionSession like UWP. However, there are some alternative approaches you can consider to achieve similar functionality.

    Alternative Approaches

    1. Using a Long-Running Background Task with COM

    Since you are using a Win32 COM background task, you can try to ensure that the task runs long enough to complete its operations. Here are some steps to help you:

    Increase the Time Trigger Interval: If possible, increase the interval of the TimeTrigger to reduce the frequency of task execution, allowing more time for each task to complete.

    Implement a Loop with Sleep: Within your background task, implement a loop that periodically checks if the task is complete and uses Thread.Sleep to wait between checks. This can help extend the execution time.

    Example Code

    Here is an example of how you might implement a long-running background task using a loop and sleep:

    public class ScheduledAutoCleanTask : IBackgroundTask
    {
        public void Run(IBackgroundTaskInstance taskInstance)
        {
            var deferral = taskInstance.GetDeferral();
            try
            {
                // Perform cleanup operations
                while (!IsCleanupComplete())
                {
                    // Perform a portion of the cleanup
                    PerformCleanupStep();
                    // Sleep for a short period to avoid CPU overuse
                    System.Threading.Thread.Sleep(1000);
                }
            }
            finally
            {
                deferral.Complete();
            }
        }
        private bool IsCleanupComplete()
        {
            // Check if the cleanup is complete
            return false; // Replace with actual condition
        }
        private void PerformCleanupStep()
        {
            // Perform a portion of the cleanup
        }
    }
    

    2. Using Extended Execution in UWP

    If your application can be adapted to UWP, you can use ExtendedExecutionSession to request additional time for background tasks. This approach is more straightforward but requires your app to be a UWP app.

    Example Code

    Here is an example of how to use ExtendedExecutionSession in UWP:

    var session = new ExtendedExecutionSession
    {
        Reason = ExtendedExecutionReason.Unspecified,
        Description = "Long-running cleanup task"
    };
    session.Revoked += SessionRevoked;
    ExtendedExecutionResult result = await session.RequestExtensionAsync();
    if (result == ExtendedExecutionResult.Allowed)
    {
        // Perform long-running task
    }
    else
    {
        // Handle the case where the extension was not granted
    }
    private void SessionRevoked(object sender, ExtendedExecutionRevokedEventArgs args)
    {
        // Handle session revocation
    }
    

    References

    I hope these suggestions help you extend the execution time of your background task in WinUI 3. If you have any further questions or need additional assistance, feel free to ask. Good luck with your project!

    Best regards,
    Jonathan


    Your feedback is very important to us! If this answer resolved your query, please click 'YES'. This helps us continuously improve the quality and relevance of our solutions. Thank you for your cooperation!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.