WindowsAppSDK icon indicating copy to clipboard operation
WindowsAppSDK copied to clipboard

UniversalBGTask crashes with STOWED_EXCEPTION

Open tipa opened this issue 3 months ago • 33 comments

Describe the bug

I added support for background tasks as described in the documentation: https://learn.microsoft.com/en-us/windows/apps/windows-app-sdk/applifecycle/background-tasks

It works for most users, but I am seeing a lot of crash reports (in the Partner Center) for all my apps published in the Microsoft Store that are using background tasks. With WinAppSDK 1.7, it was mostly ACCESS_VIOLATION errors and they have been discussed in this issue (which for some reason has been moved to the microsoft/microsoft-ui-xaml repository).

Now, after upgrading to WinAppSDK 1.8, I am still seeing crashes (seemingly the same amount - way over 10.000 crashes per day!), but with error code STOWED_EXCEPTION. Since the amount of crashes exceeds the "devices affected", it looks like the crash is happening repeatedly for the same machines.

Here are some stack traces as reported by the Microsoft Partner Center:

STOWED_EXCEPTION_80004005_Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll!_CallSettingFrame_LookupContinuationIndex

Frame  Image                                                                 Function
0      combase.dll                                                           RoOriginateLanguageException
1      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     winrt::hresult_error::originate
2      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     `winrt::to_hresult'::`1'::catch$23
3      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     _CallSettingFrame_LookupContinuationIndex
4      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     __FrameHandler4::CxxCallCatchBlock
5      ntdll.dll                                                             RcFrameConsolidation
6      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     winrt::to_hresult
7      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     `winrt::impl::root_implements_winrt::Microsoft::Windows::ApplicationModel::Background::UniversalBGTask::factory_implementation::Task,winrt::Windows::Foundation::IActivationFactory_::NonDelegatingGetTrustLevel'::`1'::catch$0
8      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     _CallSettingFrame_LookupContinuationIndex
9      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     __FrameHandler4::CxxCallCatchBlock
10     ntdll.dll                                                             RcFrameConsolidation
11     Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     winrt::impl::produce_winrt::Microsoft::Windows::ApplicationModel::Background::UniversalBGTask::implementation::Task,winrt::Windows::ApplicationModel::Background::IBackgroundTask_::Run
12     biwinrt.dll                                                           Windows::ApplicationModel::Background::CBackgroundTaskInstance::RunInternal
13     biwinrt.dll                                                           Windows::ApplicationModel::Background::CBackgroundTaskInstance::Run
14     twinapi.appcore.dll                                                   Windows::ApplicationModel::Core::BackgroundTaskWrapper::ThreadProc
15     ntdll.dll                                                             TppWorkpExecuteCallback
16     ntdll.dll                                                             TppWorkerThread
17     kernel32.dll                                                          BaseThreadInitThunk
18     ntdll.dll                                                             RtlUserThreadStart
STOWED_EXCEPTION_80004002_Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll!winrt::Microsoft::Windows::ApplicationModel::Background::UniversalBGTask::implementation::Task::Run

Frame  Image                                                                 Function
0      combase.dll                                                           RoOriginateLanguageException
1      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     winrt::hresult_error::originate
2      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     winrt::hresult_no_interface::hresult_no_interface
3      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     winrt::Microsoft::Windows::ApplicationModel::Background::UniversalBGTask::implementation::Task::Run
4      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     winrt::impl::produce_winrt::Microsoft::Windows::ApplicationModel::Background::UniversalBGTask::implementation::Task,winrt::Windows::ApplicationModel::Background::IBackgroundTask_::Run
5      biwinrt.dll                                                           Windows::ApplicationModel::Background::CBackgroundTaskInstance::RunInternal
6      biwinrt.dll                                                           Windows::ApplicationModel::Background::CBackgroundTaskInstance::Run
7      twinapi.appcore.dll                                                   Windows::ApplicationModel::Core::BackgroundTaskWrapper::ThreadProc
8      ntdll.dll                                                             TppWorkpExecuteCallback
9      ntdll.dll                                                             TppWorkerThread
10     kernel32.dll                                                          BaseThreadInitThunk
11     ntdll.dll                                                             RtlUserThreadStart
STOWED_EXCEPTION_80004005_Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll!Unknown

Frame  Image                                                                 Function
0      combase.dll                                                           RoOriginateLanguageException
1      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     -
2      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     -
3      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     -
4      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     -
5      ntdll.dll                                                             RcFrameConsolidation
6      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     -
7      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     -
8      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     -
9      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     -
10     ntdll.dll                                                             RcFrameConsolidation
11     Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     -
12     biwinrt.dll                                                           -
13     biwinrt.dll                                                           -
14     twinapi.appcore.dll                                                   Windows::ApplicationModel::Core::BackgroundTaskWrapper::ThreadProc
15     ntdll.dll                                                             TppWorkpExecuteCallback
16     ntdll.dll                                                             TppWorkerThread
17     kernel32.dll                                                          BaseThreadInitThunk
18     ntdll.dll                                                             RtlUserThreadStart
STOWED_EXCEPTION_800706ba_Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll!winrt::Microsoft::Windows::ApplicationModel::Background::UniversalBGTask::implementation::Task::Run

Frame  Image                                                                 Function
0      combase.dll                                                           RoOriginateLanguageException
1      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     winrt::hresult_error::originate
2      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     winrt::hresult_error::hresult_error
3      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     winrt::throw_hresult
4      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     winrt::Microsoft::Windows::ApplicationModel::Background::UniversalBGTask::implementation::Task::Run
5      Microsoft.Windows.ApplicationModel.Background.UniversalBGTask.dll     winrt::impl::produce_winrt::Microsoft::Windows::ApplicationModel::Background::UniversalBGTask::implementation::Task,winrt::Windows::ApplicationModel::Background::IBackgroundTask_::Run
6      biwinrt.dll                                                           Windows::ApplicationModel::Background::CBackgroundTaskInstance::RunInternal
7      biwinrt.dll                                                           Windows::ApplicationModel::Background::CBackgroundTaskInstance::Run
8      twinapi.appcore.dll                                                   Windows::ApplicationModel::Core::BackgroundTaskWrapper::Run
9      twinapi.appcore.dll                                                   Windows::ApplicationModel::Core::BackgroundTaskWrapper::ThreadProc
10     ntdll.dll                                                             TppWorkpExecuteCallback
11     ntdll.dll                                                             TppWorkerThread
12     kernel32.dll                                                          BaseThreadInitThunk
13     ntdll.dll                                                             RtlUserThreadStart

NuGet package version

Windows App SDK 1.8.1: 1.8.250916003

Packaging type

Packaged (MSIX)

Windows version

Windows 11 version 24H2 LTSC (26100, June Update)

IDE

Visual Studio 2022

Additional context

Crashes happen on various Windows versions, e.g. Windows 11 10.0.26100, Windows 11 10.0.22631, Windows 10 10.0.19045, ...

tipa avatar Sep 29 '25 10:09 tipa

I had a look into these crash dumps, and the crash is happening as CoCreateInstance fails and throws exception. On further checking the etl files, below are some relevant ones I am seeing

Warning: PackagedCom entry for {B949185E-9ADC-4FD4-84B9-DAF90D64A3FB} in package 49297T.Partl.ClockOut_2.15.3.0_x64__jr9bq2af9farr (and possibly others) exists but is not visible to the caller. Lookup was performed without per-user state, which may indicate that the caller was elevated, non-user, or otherwise blocks per-user registrations (e.g. UWP and some OS processes).

Package 49297T.Partl.ClockOut_2.15.3.0_x64__jr9bq2af9farr is not singleton or system registered

Call security blocked activation call: CLSID:{B949185E-9ADC-4FD4-84B9-DAF90D64A3FB}, Client PID (image):6654 (C:\WINDOWS\system32\backgroundTaskHost.exe), Server PID (image): 0x60c4 (C:\Program Files\WindowsApps\49297T.Partl.ClockOut_2.15.3.0_x64__jr9bq2af9farr\WorkingHours.exe)

Can you once check whether the LaunchAndActivationPermissions are set appropriately as done in the sample here

godlytalias avatar Oct 14 '25 20:10 godlytalias

Yes, LaunchAndActivationPermissions is set exactly like that. I think the background task is working as intended for most users, and if LaunchAndActivationPermissions wasn't set properly, it wouldn't work for any?

tipa avatar Oct 14 '25 20:10 tipa

@godlytalias please let me know if you need any additional information from me. Is it possible that crash happens when the WinAppSDK Runtime hasn't been properly installed alongside WorkingHours? Or has been uninstalled forcefully later on? I've heard from instances where this happened. For one of my apps I am now seeing almost 15.000 (!) crashes per day - and it's still an upwards trend

tipa avatar Oct 22 '25 09:10 tipa

@tipa Its not related to WinAppSDK Runtime, I can see the UniversalBGTask operations being executed, but the above COM class IDs mentioned is from your app right? Errors say that the CoCreateInstance for these COM classes fail as it is not found in the package.

@DrusTheAxe Whether you have any clue on why these package related errors happen, https://github.com/microsoft/WindowsAppSDK/issues/5870#issuecomment-3403442863

godlytalias avatar Oct 22 '25 09:10 godlytalias

@godlytalias Yes, that is the GUID for my background task. It's certainly in the app, you can test it yourself :) As I said, from what I can tell the background task basically works for most users. Isn't there a way to handle this error in your code so that it doesn't crash my app?

tipa avatar Oct 22 '25 10:10 tipa

@tipa Ignoring CoCreateInstance failures would be problematic, In that case we may not be able to know of real issues where the tasks are not running. Right path here would be to identify the issue with the package here and get it fixed. Anyway user experience would be same in this case as well as if we simply ignore the failure. Crash would be for backgroundtaskhost.exe process, not the app process

godlytalias avatar Oct 22 '25 10:10 godlytalias

@godlytalias I'd totally prefer if you could find the underlying issue, but from a developer perspective handling or not handling the error does make a difference. At the moment, my crash reporting in the Partner Center is totally flooded with those crashes and it makes it so much harder to identify the crashes I am actually able to fix. Additionally, getting so many crashes can have an impact on the Store ranking algorithm and potentially cause my app to become less visible in the Store.

Would this crash happen when not calling CoRegisterClassObject? I've identified many cases in which my app throws an exception on startup (caused by the WinAppSDK - I've already reported them here). I am currently catching those errors and gracefully exit the app, without calling CoRegisterClassObject (I call that method in my Apps constructor).

tipa avatar Oct 22 '25 11:10 tipa

If the COM server don't do CoRegisterClassObject, that would fail the CoCreateInstance for sure. But I am not sure whether that is the only cause for crashes here. @DrusTheAxe may have some clues from package deployment perspective.

godlytalias avatar Oct 22 '25 12:10 godlytalias

I made sure to call CoRegisterClassObject before anything else in my app, as first instruction in the Program.Main() method (I'm using a single-instanced app, if that's of relevance here) - without luck.

I have found yet another oddity with this background task implementation. When I omit RuntimeIdentifier in my csproj file, the background task just never fires, and I also don't see a crash. Why?

Going through the sample, I also noted this line in which ComServer.CoRevokeObject is called. Is this of importance? If yes, why and if no, why is it included in the sample?

Same question about this part. Is WindowsAppSDKBackgroundTask=true in the csproj really required? It seems to work without it in my apps. Why is it documented as being required?

In the meatime, my crash count keeps rising every day and since there doesn't seem to be any fix on the horizon, I will at some point have to consider to remove the entire background task from my app again.

tipa avatar Oct 31 '25 12:10 tipa

If you omit RuntimeIdentifier, I guess it may not be deploying the universalbgtask.dll as well, you can see whether the dll is getting included in the package. Also about the point 'seeing a crash', these crashes in the spikes are from backgroundtaskhost.exe, which would not crash the 'main application process'. I think you may have to look into 'Diagnostic Data Viewer' -> Problem Reports tab / search for Microsoft.Windows.BrokerInfrastructure.* telemetry to see what is the status of the tasks (If that is not the way you're checking crash).

ComServer.CoRevokeObject does the cleanup operations when COM server shuts down, so that COM doesn't call into a dead server handle. This may be required when application closes. This can be a catch if not being done.

WindowsAppSDKBackgroundTask=true is not required for C# projects, as the binaries gets placed during publish operations otherwise as well. Its required for cppwinrt projects only.

If you're having so much crash count, there should be some way to repro the issue, if you can share a repro, it would be easy to figure out root cause (as mentioned above you should not be looking for the app process crashing, it would be backgroundtaskhost.exe which would be crashing). From the crash dumps what I can find out is that, the COM server looks for creating instance of the background task class registered, but that fails.

godlytalias avatar Oct 31 '25 14:10 godlytalias

Also about the point 'seeing a crash', these crashes in the spikes are from backgroundtaskhost.exe, which would not crash the 'main application process'.

When I'm referring to a "crash" then I mean a "Crash" as reported by the Partner Center in the "Health" tab and these are a problem for me.

Image

I think you may have to look into 'Diagnostic Data Viewer' -> Problem Reports tab / search for Microsoft.Windows.BrokerInfrastructure.* telemetry to see what is the status of the tasks (If that is not the way you're checking crash).

I don't think these crashes are coming from my machines, so I won't be able to gather contextual information in the Diagnostic Data Viewer. Searching for Microsoft.Windows.BrokerInfrastructure.* yields no results.

ComServer.CoRevokeObject does the cleanup operations when COM server shuts down, so that COM doesn't call into a dead server handle. This may be required when application closes. This can be a catch if not being done.

  • If this is required (is it really?) why is it not mentioned in the documentation here?
  • Looking at just that very documentation, it is noted that
    The background task class itself—and all other classes in the background task project—need to be public.
    
    but is this really the case? My BackgroundTask is internal and it works as expected - why? Or is this even the correct documentation for my case? It contains code about RegistrationServices that is nowhere to be found in the example app. It is really confusing
  • I'm also using the CoRegisterClassObject approach to integrate into the Windows widget panel, and that component doesn't crash at all - at least I see no related crash reports in the Partner Center
  • I can try to call CoRevokeObject and report back if that changes things, but I don't have much hope to be honest, given all my previous changes didn't improve the situation either. If using this method is really required, why is it not documented anywhere, only used in the example project? Additionally, from what I can tell basd on a few quick tests, the App deconstructor is never called.

WindowsAppSDKBackgroundTask=true is not required for C# projects, as the binaries gets placed during publish operations otherwise as well. Its required for cppwinrt projects only.

Would you agree that the sample should be fixed then? It currently is in the C# project sample with the note This tag is required for the usage of WinAppSDK Background Task API

If you're having so much crash count, there should be some way to repro the issue, if you can share a repro, it would be easy to figure out root cause (as mentioned above you should not be looking for the app process crashing, it would be backgroundtaskhost.exe which would be crashing). From the crash dumps what I can find out is that, the COM server looks for creating instance of the background task class registered, but that fails.

As I wrote before, I don't think the crashes originate from my machine, nor from machines of the majority of users. The Partner Center reports that the 15.000 crashes originate from just 460 devices (and I have much more daily active users). So that makes 32 crashes per devices on an average day. I am using a background task with a 15 minute TimeTrigger - that would perfectly match a regular 8 hour work day (4 crashes per hour)

Image

What I can do is share a trimmed down example project that shows how I have implemented the background task. Would that help?

tipa avatar Oct 31 '25 16:10 tipa

You're referring to the Platform SDK Documentation which have been there for quite some time. I don't have the context of all those points. However I feel its fair point that the background task class need to be public as it need to be invoked by an external component. CoRevokeClassObject is required however, I can see that in the sample as well in the doc link you shared, More details can be seen in the CoRevokeClassObject docs as well, https://learn.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-corevokeclassobject (not CoRevokeObject, winappsdk sample to be fixed) WindowsAppSDKBackgroundTask=true is to be fixed in C# case from winappsdk targets file itself, Currently it is working through C# publishing mechanism, hence even the apps that don't require background task ends up having those universalbgtask binaries. In upcoming versions this need to be fixed that only apps which have this flag will have those binaries packaged. I would suggest to fix the revoke operation and once see whether crash count goes down

godlytalias avatar Oct 31 '25 18:10 godlytalias

Thanks for the quick response. It's a bit irritating that there's a documented need for the class to be public, but it appears to be working even when the visibility is internal. Shouldn't it not work at all if it's internal? Well I'll make it public and also call the CoRevokeClassObject method and report back in a few days! I will also try to prepare a sample project that shows how I implemented the background task in my app.

When using the single-instanced app model, should I be calling CoRevokeClassObject in the Main method as seend below instead of the Apps constructor?

static class Program
{
    static uint token1, token2;

    [STAThread]
    static void Main()
    {
        try
        {
            NativeMethods.CoRegisterClassObject(typeof(WidgetProvider).GUID, new WidgetProviderFactory(), 4, 1, out token1);
            NativeMethods.CoRegisterClassObject(typeof(BackgroundTask).GUID, new BackgroundTaskFactory(), 4, 1, out token2);

            var keyInstance = AppInstance.FindOrRegisterForKey("main");
            if (keyInstance.IsCurrent)
            {
                keyInstance.Activated += (_, e) => App.HandleAppActivation(e);
                Application.Start(p =>
                {
                    var context = new DispatcherQueueSynchronizationContext(DispatcherQueue.GetForCurrentThread());
                    SynchronizationContext.SetSynchronizationContext(context);
                    _ = new App();
                });
            }
            else { Tools.RedirectAppActivation(keyInstance); }
        }
        catch (Exception e) { Tools.HandleStartupException(e); }// https://github.com/microsoft/WindowsAppSDK/issues/5694

        // https://github.com/microsoft/WindowsAppSDK/issues/5870#issuecomment-3474298468
        NativeMethods.CoRevokeClassObject(token1);
        NativeMethods.CoRevokeClassObject(token2);
    }
}

...

[LibraryImport("ole32.dll")]
public static partial int CoRegisterClassObject(
    in Guid classId, [MarshalAs(UnmanagedType.Interface)] IClassFactory objectAsUnknown,
    uint executionContext, uint flags, out uint registrationToken);

[LibraryImport("ole32.dll")]
public static partial int CoRevokeClassObject(uint registrationToken);

tipa avatar Oct 31 '25 22:10 tipa

@godlytalias After uploading a new version where I also call CoRevokeClassObject (not to my surprise) nothing has changed. The crash rate persisted and I now see almost 17.000 crashes per day - for a single app.

Please see the attached test project where I tried to replicate the implementation of the feature. It would be great if you could point out what I am doing wrong: App1.zip

If it matters, this is the script I am using to build Release versions of my app: build.zip

Despite spending days on the topic and making numerous of changes, I still get this extreme amount of crashes. It makes the Health report in the Partner Center completely useless for me and it potentially has a negative impact on Store ranking. Is there any workaround for implementing time-triggered background tasks or for the UserPresent/UserAway/SessionConnected triggers?

tipa avatar Nov 06 '25 14:11 tipa

@tipa Is your app AOT? If yes, you could simply author your own WinRT IBackgroundTask component without even using the Windows App SDK universal task. https://github.com/microsoft/CsWinRT/tree/master/src/Samples/BgTaskComponent

If your app is not AOT but .NET self-contained, it won't work directly due to a bug, but there is a workaround using DNNE. https://github.com/microsoft/CsWinRT/issues/1141#issuecomment-1074293306

The task will only run with AppContainer permissions however

BernhardMarconato avatar Nov 06 '25 17:11 BernhardMarconato

As I checked the sample app provided, its not having appcontainer. So issues would not be related to appcontainer case it seems. However this crash seems to happen if an application instance is running in High IL while the background task is trying to be invoked as COM activation from backgroundtaskhost will fail in that case. But its quite unbelievable that we have lot of such instances. If we don't want high IL case, we can go with AppContainer so that app won't get launched in High IL. Or else if high IL to be supported, we may need to update the security config for allowing the COM activation, https://learn.microsoft.com/en-us/windows/win32/com/setting-processwide-security-with-coinitializesecurity @tipa Whether there is possibility of application being launched in high IL (run as administrator) and kept open forever?

godlytalias avatar Nov 07 '25 07:11 godlytalias

@BernhardMarconato thanks for the suggestion. Yes I am using NativeAOT - I will have a look at the code you referenced. I says it's about out-of-process background task while I believe I need in-process background tasks, but let's see.

@godlytalias I don't have exact numbers, but I believe my app is installed on tens of thousands of devices (Partner Center reports 85.000 installs in the last 12 months and my app is around since 8.5 years). It is certainly possible that on the ~500 devices this issues seems to occur on, the app is launched as Administrator. I have had conversations with customers in the past where this was the case. I don't know why they would launch my app with elevated priviledges or in what context this would be necessary (maybe on Windows Server instances...?), but it would certainly explain why this issue only occurs for a very small percentage of my users and breaks down to 32 crashes per day per affected user (one crash per 15 minutes, which is the specified TimeTrigger). Also, I did try to reproduce it locally with my app launched as Administrator and it indeed causes an error being logged in the Event Viewer:

Image

tipa avatar Nov 10 '25 11:11 tipa

@tipa I checked your sample from the perspective of an app instance being launched with elevated privileges, In this scenario when the background task triggers and COM activation happens, it won't be able to find the existing COM server running in high IL and so creates a new process instance in medium IL, but this process does the CoRegisterClassObject, does the RedirectActivationAsync and then exits without waiting for background task to execute, this leads to the crash. To fix this, if we move the SetEvent logic from main method to the Run method of background task, then the COM server process would be running until background task finish execution and the crash would not happen, you may have to note that the execution happen in a medium IL process instance though (not in the other high IL process running)

godlytalias avatar Nov 10 '25 14:11 godlytalias

@godlytalias Thanks for your explanation, it totally makes sense and I was able to verify this in my tests. The background task being executed in a different process isn't what I need, since I am accessing data that is in my main process. So I will likely add some logic that exits early from my background task Run() method if the process was launched with the -bgtask command line argument and keyInstance.IsCurrent == false and also waiting for the background task to be invoked before exiting the process. I hope this reliably handles this particular case and stops the crashes.

What I find a bit odd is that widget providers seem to be using a very similar concept like the background tasks, but in my tests they do not cause any crashes if my main app is being launched as administrator and then accessing the widget board, which causes a new, medium IL process of my app being launched. I don't know why this is the case. Maybe the widget panel does COM activation earlier, while my process is still alive?

If this high IL / medium IL thing turns out to be the reason for my crashes, will there be any effort to handle this case in the WinAppSDK? Is there a way to get in-process background tasks working in high IL? If not, would it be possible to simply not launch a new process of my app if a high IL process is already running?

tipa avatar Nov 11 '25 07:11 tipa

As you mentioned, the widget related COM server would be keeping itself alive until the COM call finishes unless you set appropriate access permissions explicitly.

To support in High IL you have to give AccessPermissions for a process to access it while running in High IL, https://learn.microsoft.com/en-us/windows/win32/com/setting-processwide-security-through-the-registry In case you want to explore that route for setting permissions, you can use this editor to modify the registry. Here’s an example of a pretty normal AccessPermissions SD in SDDL: O:BAG:BAD:(A;;0x3;;;BA)(A;;0x3;;;SY)(A;;0x3;;;PS)(A;;0x3;;;AC) This allows in machine-local calls from admin, system, and self (i.e. the user this process is running as), and also allows calls from AppContainers which meet those previous criteria. Another option is to call CoInitializeSecurity, but this call have to be done before COM initializes, as yours is a .net app, its not that reliable as .net may initialize COM before you do this call.

If not given AccessPermissions as soon as a CoCreateInstance call happens, COM looks for an existing server and if it don't find any accessible ones, it will create a new server process.

godlytalias avatar Nov 11 '25 10:11 godlytalias

I feel like this is where my technical understanding of COM and all this really ends. Implementing background tasks that don't crash shouldn't be so difficult (and it wasn't on UWP!).

Will there be changes to how background tasks are implemented in the WinAppSDK or is this "working as intended"?

tipa avatar Nov 11 '25 22:11 tipa

This is 'working as intended', because if you have a High IL process and you haven't set AccessPermissions, the security layer won't allow another process to access an object in the High IL process, so COM ends up launching another Medium IL process to carry out the tasks then. As I get time, I can update the In-Proc background task samples to showcase the use of AccessPermissions as well.

godlytalias avatar Nov 12 '25 04:11 godlytalias

@godlytalias I'm a bit surprised to hear that, because I can imagine that most other developers using background tasks would run into the very same issue. There is currently no documentation (that I could find) about this issue and the implementation already is very complex that requires a good understanding of COM and other Windows-specifics. As a comparison, implementing in-process periodic background tasks in iOS, Android and also UWP was straight-foward, a very simple-to-use with a minimal API.

I have not set AccessPermissions because I don't know anything about it and there is no mention of it in the documentation. I don't know what the next steps would be for me to fix this issue. I'd very much appreciate an update of the in-proc task examples that also fix the other issues that I pointed out in my previous posts.

As a test, I used the SDDL you showed as an example, but it caused an error during compilation: DEP0700: Registration of the app failed. [0x80080204] error 0xC00CE169: App manifest validation error: The app manifest must be valid as per schema: Line 40, Column 99, Reason: 'O:BAG:BAD:(A;;0x3;;;BA)(A;;0x3;;;SY)(A;;0x3;;;PS)(A;;0x3;;;AC)' violates pattern constraint of '(O:[A-Z0-9\-]*)?(G:[A-Z0-9\-]*)?(D:[PARI]*(\([A-Z0-9\-;]*\))*)?(S:[PARI]*(\([A-Z0-9\-;]*\))*)?'. ...

tipa avatar Nov 13 '25 07:11 tipa

I have now implemented my workaround that prevents the new (medium IL) process from shutting down immediately. But it didn't help, crash count stayed the same and even increased. I'm not at 20.000 crashes per day for a single app, tried dozens of adjustments and tweaks and have no idea what I could try next. This is frustrating

tipa avatar Nov 15 '25 23:11 tipa

I guess the devices which are causing crash may have configured built-in administrator account enabled and the user would be built-in administrator in which case it won't launch medium IL process? (May be good to test and confirm this case), In those cases as well the solution would be on enabling the accesspermissions only, I will add that workaround to the sample soon, basically we have to add a registry.dat file to the package with those registry entries that gives privileges for accessing High IL.

Regarding App manifest validation error, I think it may be because of hex values, try giving 3 instead of 0x3.

godlytalias avatar Nov 16 '25 00:11 godlytalias

I have no idea how my customers have configured their Windows machines and I don't know how to test these cases (I'd expect Microsoft to do that). I would greatly appreciate an update to the sample that works.

I tested adjusting the LaunchAndActivationPermission and while the app now launches, it still crashes - see the updated example: App1.zip

tipa avatar Nov 17 '25 22:11 tipa

For fixing this issue we don't have to change LaunchAndActivtionPermission that would remain same as early, what we have to do is setting AccessPermission in registry as mentioned here, https://learn.microsoft.com/en-us/windows/win32/com/setting-processwide-security-through-the-registry On some further debugging it seems there are some underlying COM bugs as well in the OS that need to be addressed regarding HighIL cases, doing some internal discussions regarding that. Will update here once I get an update.

godlytalias avatar Nov 20 '25 15:11 godlytalias

@godlytalias thanks for the update. Is there anything I can do now to contain the problem or will I have to wait for a new WinAppSDK update? E.g. can I detect if my app runs in HighIL and simply not register my background tasks for those instances? I really hope no fix on the OS side will be required, since then it would take forever for this change to be rolled out and my crash count to decrease.

Also, I still didn't quite understand why these crashes happen for the background task component, but not for the widgets which - from what I understand - are using a very similar approach using COM, CoRegisterClassObject etc

tipa avatar Nov 21 '25 06:11 tipa

I also often see this Debug output when debugging my app (in MediumIL). It doesn't cause a crash and no even is logged in the Windows Event Viewer - but it don't think this is supposed to happen

The target process exited without raising a CoreCLR started event. Ensure that the target process is configured to use .NET Core. This may be expected if the target process did not run on .NET Core.
The program '[48400] backgroundTaskHost.exe' has exited with code 1 (0x1).
The thread 34428 has exited with code 0 (0x0).

tipa avatar Nov 24 '25 10:11 tipa

@tipa While waiting for the bugfix / workarounds, One thing can be done is to skip registering background task / clear background task if process is launched in high IL to ensure that the issue is with the high IL case as we assume. Widgets case seems to be working fine as the COM launch is not happening from app container similar to background tasks, bug seems to be with COM launch from app container. The debug output you mentioned I guess may be because you're trying to do 'managed debugging' with backgroundtaskhost process which is not managed

godlytalias avatar Nov 25 '25 13:11 godlytalias