WindowsAppSDK icon indicating copy to clipboard operation
WindowsAppSDK copied to clipboard

ThemeSettings Crashing application

Open viniciuscabral opened this issue 1 year ago • 2 comments

Describe the bug

For some reason when I use ThemeSettings to watch the Changed event, the application crashes with an internal error from SDK. It happens in two scenarios: 1 - When I use ThemeSettings like a local variable 2 - When I use ThemeSettings like a global variable in a single instance class

Steps to reproduce the bug

I create an app with two Pages and move back and forth between them.

First scenario you can use it like that in the Loaded event in the second Page.

 if (this.XamlRoot != null && this.XamlRoot.ContentIslandEnvironment != null)
 {
     WindowId myWindowId = this.XamlRoot.ContentIslandEnvironment.AppWindowId;
    var _themeSettings = ThemeSettings.CreateForWindowId(myWindowId);

     if (_themeSettings != null)
     {
         _themeSettings.Changed += ThemeSettings_Changed;
     }
 }

In some moments the App Crashes...

The second scenario just replaces var _themeSettings for a global variable and moves the code to a singleton class. Both crashes the same way.

I suppose it can happen because the Changed event isn't explicitly unsubscribed... But I believe it's an unhandled exception in the SDK source code. To solve the problem by now, I'm checking if _themeSettings is not null before CreateForWindowId and Unbscribe the Changed event in the Unload page Event, but I'm not sure if other crashes can reside.

Expected behavior

Do not crash the app.

Screenshots

Image No valuable information actually.

NuGet package version

WinUI 3 - Windows App SDK 1.6.3: 1.6.241114003

Windows version

Windows 11 (22H2): Build 22621

Additional context

No response

viniciuscabral avatar Jan 14 '25 13:01 viniciuscabral

I have the same issue, except that it is in a C++ application and using WinAppSDK 1.8.

~From my debugging, it seems to be a bug with reference counting in the SDK. The crash happens when trying to release the ThemeSettings. Artificially increasing the reference count (by copying the pointer and then detaching it) seems to work around this.~ Edit: I was totally wrong. See the comment below

florelis avatar Oct 14 '25 21:10 florelis

Hi, I took a look at the code -- it looks like we'll get this exception in this case:

A ThemeSettings object with active event handlers... 1, ...gets destroyed off-thread, OR 2. ...after the window it's attached to gets destroyed.

To avoid the exception: as suggested above, you can unsubscribe the event handler before the top-level window closes.

I agree it would be nice to fix this so that the ThemeSettings object can gracefully handle this case, leaving this open.

(PS -- we should probably move this to the WinAppSDK repo since this isn't Xaml-related)

JesseCol avatar Oct 15 '25 22:10 JesseCol