I have a fairly complex WinUI 3 desktop app (v1.2, .NET 7, x64 in Debug mode) that keeps failing (after a specific sequence of events only) with a message from Visual Studio 2022 Enterprise in the Output
window that says:
The program '[28716] xxxxxxx.exe' has exited with code 3221225477 (0xc0000005) 'Access violation'.
The app starts a secondary window on the UI thread with
if (App.ShellPage.SettingsStatusWindow)
{
StatusWindow = new StatusWindow(); // create new window
StatusWindow.Activate();
}
else
{
WeakReferenceMessenger.Default.Send(new CloseWindowMessage()); // close windows
}
and StatusWindow
is closed in the CloseWindowMessage
handler like so
WeakReferenceMessenger.Default.Register<CloseWindowMessage>(this, (r, m) =>
{
WeakReferenceMessenger.Default.Unregister<TraceMessage>(this);
WeakReferenceMessenger.Default.Unregister<CloseWindowMessage>(this);
Close();
});
if a CloseWindowMessage
is received or in the StatusWindow_Closed
handler if the Close
button on the the StatusWindow
title bar is clicked.
private void StatusWindow_Closed(object sender, WindowEventArgs args)
{
Closed -= StatusWindow_Closed;
WeakReferenceMessenger.Default.UnregisterAll(this);
WeakReferenceMessenger.Default.Send(new WindowClosedMessage());
}
The WeakReferenceMessenger
class is from CommunityToolkit.Mvvm.Messenger
.
Although the message is in the Output
window, it is not from any Trace
or Debug
code and does not seem to raise any catchable Exception
as App
startup includes:
UnhandledException += App_UnhandledException;
System.AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Microsoft.UI.Xaml.Application.Current.UnhandledException += Current_UnhandledException;
but no handler gets called.
My best guess is that somehow, a message is being sent to either a Closing
StatusWindow
after it has unregistered for messages, or a Closed
StatusWindow
. Curiously, closing a StatusWindow
by sending a CloseWindowMessage
will cause the violation within about a second whereas closing the StatusWindow
once by clicking the Close
button not only doesn't cause the error, but any new StatusWindows
opened afterward never cause the error regardless of how they're closed. This makes me wonder if it's an initialization issue.
I've tried to isolate the problem by stripping out all the other logic and building a small app with just the window, but I can't seem to generate the Access violation
error.
Any ideas on how I can get .NET to throw a catchable error to help troubleshoot? Alternatively, an suggestions on how I might isolate the offending message or object reference? Many thanks in advance.