Getting LaunchActivatedEventArgs crashes in release mode
Describe the bug
See the attached repro project. When getting the activation arguments in Main (App.xaml.cs), the application will crash with a System.NullReferenceException. Please note that this only happens in Release (x64) mode with PublishReadyToRun enabled (the default value). ActivationArgsRepro.zip
The following change seems to somehow workaround this issue
AppActivationArguments activatedArgs = AppInstance.GetCurrent().GetActivatedEventArgs();
Windows.ApplicationModel.Activation.LaunchActivatedEventArgs launchArgs = activatedArgs.Data as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
launchArgs.Kind.ToString(); // Add this line to avoid a crash
if (launchArgs.Arguments.StartsWith("argument"))
{
}
Steps to reproduce the bug
- Run the attached repro project in Release mode (x64)
Expected behavior
No response
Screenshots
No response
NuGet package version
1.1.4
Packaging type
Packaged (MSIX)
Windows version
Windows 11 version 21H2 (22000)
IDE
Visual Studio 2022
Additional context
No response
This is reproable. @lhak thank you for the repro project.
After doing some light debugging the error is coming from Windows.ApplicationModel.Activation.LaunchActivatedEventArgs launchArgs = activatedArgs.Data as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs; This throws Null Reference Extension.
What is odd is that activatedArgs.Data isn't null. Found with a if(activatedArgs.Data == null) {log null} else {log not null}
Next, I added activatedEventArgs.Kind.ToString(); Fixed the issue. I found it odd though, that adding a line, that does nothing, makes this work.
I tried something else. Instead of activatedEventArgs.Kind.ToString() I did Thread.Sleep(1000). App runs fine.
Looks like an optimization, somewhere, is causing a race condition where args.Data isn't null, yet, casting it causes a null reference exception. @MikeHillberg Does a race condition with WinUI3 sound familiar?
Changing as to a cast throws an error, even with THread.Sleep.
var activatedArgsAsSomethingLese = (Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)activatedEventArgs.Data;
Still runs fine in debug.
Getting closer.
I printed the .ToString of 1activatedEventArgs.Data` Here are the results Debug: Windows.ApplicationModel.Activation.LaunchActivatedEventArgs Release (No sleeping): WinRT.IInspectable Release (Sleeping): WinRT.IInspectable
Combining
AppActivationArguments activatedArgs = AppInstance.GetCurrent().GetActivatedEventArgs(); and
Windows.ApplicationModel.Activation.LaunchActivatedEventArgs launchArgs = activatedArgs.Data as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
Into MyData = AppInstance.GetCurrent().GetActivatedEventArgs().Data as Windows.ApplicationModel.Activation.LaunchActivatedEventArgs;
does not crash in release.
@lhak Combining the two calls into one works for mitigating the issue.
I'm still looking into why this is happening.