dotnet / maui

.NET MAUI is the .NET Multi-platform App UI, a framework for building native device applications spanning mobile, tablet, and desktop.
https://dot.net/maui
MIT License
22.21k stars 1.75k forks source link

WinRt exception when page navigated #22790

Open davide-cavallini opened 5 months ago

davide-cavallini commented 5 months ago

Description

When the app navigate between two pages randomly crashes. In the second page my app is trying to deserialize a json file to runtime create the UI.

Steps to Reproduce

  1. Run the sample
  2. Navigate for a while from "MainPage" to "Page2"
  3. Watch the app crash

To speed up the process I've used a tool for automatic clicking ([https://tinytask.net/download.html])

Link to public reproduction project repository

https://github.com/davide-cavallini/WinRtExceptionTest

Version with bug

8.0.40 SR5

Is this a regression from previous behavior?

Not sure, did not test other versions

Last version that worked well

Unknown/Other

Affected platforms

Windows

Affected platform versions

No response

Did you find any workaround?

Didn't find a specific workaround, but calling Task.Sleep(n) before navigation seems to reduce the frequency of exception happening.

Relevant log output

'WinRtExceptionTest.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.5\System.Collections.Immutable.dll'. 
   at WinRT.ExceptionHelpers.<ThrowExceptionForHR>g__Throw|39_0(Int32 hr)
   at ABI.Microsoft.UI.Xaml.Controls.IContentPresenterMethods.set_Content(IObjectReference _obj, Object value)
   at Microsoft.Maui.Platform.StackNavigationManager.OnNavigated(Object sender, NavigationEventArgs e)
   at ABI.Microsoft.UI.Xaml.Navigation.NavigatedEventHandler.Do_Abi_Invoke(IntPtr thisPtr, IntPtr sender, IntPtr e)
--- End of stack trace from previous location ---
   at WinRT.ExceptionHelpers.<ThrowExceptionForHR>g__Throw|39_0(Int32 hr)
   at ABI.Microsoft.UI.Xaml.Controls.IFrameMethods.GoBack(IObjectReference _obj, NavigationTransitionInfo transitionInfoOverride)
   at Microsoft.Maui.Platform.StackNavigationManager.NavigateTo(NavigationRequest args)
   at Microsoft.Maui.CommandMapper.InvokeCore(String key, IElementHandler viewHandler, IElement virtualView, Object args)
   at Microsoft.Maui.Controls.Handlers.ShellSectionHandler.SyncNavigationStack(Boolean animated, NavigationRequestedEventArgs e)
   at Microsoft.Maui.Controls.ShellSection.OnPopAsync(Boolean animated)
   at Microsoft.Maui.Controls.ShellSection.GoToAsync(ShellNavigationRequest request, ShellRouteParameters queryData, IServiceProvider services, Nullable`1 animate, Boolean isRelativePopping)
   at Microsoft.Maui.Dispatching.DispatcherExtensions.<>c__DisplayClass3_0.<<DispatchAsync>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.Maui.Dispatching.DispatcherExtensions.<>c__DisplayClass2_0`1.<<DispatchAsync>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.Maui.Controls.ShellNavigationManager.GoToAsync(ShellNavigationParameters shellNavigationParameters, ShellNavigationRequest navigationRequest)
   at WinRtExceptionTest.Page2.<AddContainer>b__4_0()
github-actions[bot] commented 5 months ago

Hi I'm an AI powered bot that finds similar issues based off the issue title.

Please view the issues below to see if they solve your problem, and if the issue describes your problem please consider closing this one and thumbs upping the other issue to help us prioritize it. Thank you!

Open similar issues:

Closed similar issues:

Note: You can give me feedback by thumbs upping or thumbs downing this comment.

jaosnz-rep commented 5 months ago

Hi @davide-cavallini, I can't open your sample link. Can you reattach the sample to help us reproduce the error? Thank you for your patience.

davide-cavallini commented 5 months ago

Hi @jaosnz-rep. The repo was private. Now it's public. My bad, sorry for the inconvenience.

jaosnz-rep commented 5 months ago

Using sample project and automatic click tools can reproduce this issue at Windows platform. Usually, you need to click repeatedly to dozens of times. The test version 8.0.40. image

Adan0s commented 4 months ago

We're experiencing a similiar issue only on windows when navigating back via Shell.Current.GoToAsync(".."). Sometimes it takes 20 navigations back and forth, sometimes five. Stacktrace ends with System.Runtime.InteropServices.COMException without any message.

qjustfeelitp commented 3 months ago

We have experienced this and came up with a workaround. The initial fix was creating our own StackNavigationManager that would navigate with Polly retries with just repeating the setting of the page's content, if that fails then the process is repeated with a new mauicontext.

`internal sealed class ExtendedNavigationViewHandler : NavigationViewHandler { private StackNavigationManager? stackNavigationManager;

/// <inheritdoc />
protected override StackNavigationManager CreateNavigationManager()
{
    return this.stackNavigationManager ??= new ExtendedStackNavigationManager(this.MauiContext!);
}

/// <summary>
/// This is basically copy of base class with modifications in <see cref="OnNavigated"/>
/// </summary>
private sealed class ExtendedStackNavigationManager : StackNavigationManager
{
    private IView? currentPage;
    private Frame? navigationFrame;
    private Action? pendingNavigationFinished;
    private bool connected;
    private IStackNavigation? NavigationView { get; set; }

    /// <inheritdoc />
    public ExtendedStackNavigationManager(IMauiContext mauiContext) : base(mauiContext)
    { }

    public override void Connect(IStackNavigation navigationView, Frame frame)
    {
        this.connected = true;

        if (this.navigationFrame != null)
        {
            this.navigationFrame.Navigated -= OnNavigated;
        }

        FirePendingNavigationFinished();

        this.navigationFrame = frame;

        this.navigationFrame.Navigated += OnNavigated;
        this.NavigationView = navigationView;

        if (this.WindowManager?.RootView is NavigationView nv)
        {
            nv.IsPaneVisible = true;
        }
    }

    public override void Disconnect(IStackNavigation navigationView, Frame frame)
    {
        this.connected = false;

        if (this.navigationFrame != null)
        {
            this.navigationFrame.Navigated -= OnNavigated;
        }

        FirePendingNavigationFinished();
        this.navigationFrame = null;
        this.NavigationView = null;
    }

    public override void NavigateTo(NavigationRequest args)
    {
        IReadOnlyList<IView> newPageStack = new List<IView>(args.NavigationStack);
        var previousNavigationStack = this.NavigationStack;
        int previousNavigationStackCount = previousNavigationStack.Count;
        bool initialNavigation = this.NavigationStack.Count == 0;

        // User has modified navigation stack but not the currently visible page
        // So we just sync the elements in the stack
        if (!initialNavigation &&
            (newPageStack[^1] ==
             previousNavigationStack[previousNavigationStackCount - 1]))
        {
            SyncBackStackToNavigationStack(newPageStack);
            this.NavigationStack = newPageStack;
            FireNavigationFinished();

            return;
        }

        var transition = GetNavigationTransition(args);
        this.currentPage = newPageStack[^1];

        _ = this.currentPage ?? throw new InvalidOperationException("Navigation Request Contains Null Elements");

        if (previousNavigationStack.Count < args.NavigationStack.Count)
        {
            var destinationPageType = GetDestinationPageType();
            this.NavigationStack = newPageStack;
            this.navigationFrame?.Navigate(destinationPageType, null, transition);
        }
        else if (previousNavigationStack.Count == args.NavigationStack.Count)
        {
            var destinationPageType = GetDestinationPageType();
            this.NavigationStack = newPageStack;
            this.navigationFrame?.Navigate(destinationPageType, null, transition);
        }
        else
        {
            this.NavigationStack = newPageStack;
            this.navigationFrame?.GoBack(transition);
        }
    }

    protected override Type GetDestinationPageType()
    {
        return typeof(Page);
    }

    protected override NavigationTransitionInfo? GetNavigationTransition(NavigationRequest args)
    {
        if (!args.Animated)
        {
            return null;
        }

        // GoBack just plays the animation in reverse so we always just return the same animation
        return new SlideNavigationTransitionInfo
        {
            Effect = SlideNavigationTransitionEffect.FromRight
        };
    }

    private void SyncBackStackToNavigationStack(IReadOnlyList<IView> pageStack)
    {
        if (this.navigationFrame is null)
        {
            return;
        }

        // Back stack depth doesn't count the currently visible page
        int nativeStackCount = this.navigationFrame.BackStackDepth + 1;

        // BackStack entries have no hard relationship with a specific IView
        // Everytime an entry is about to become visible it just grabs whatever
        // IView is going to be the visible so all we're doing here is syncing
        // up the number of things on the stack
        while (nativeStackCount != pageStack.Count)
        {
            if (nativeStackCount > pageStack.Count)
            {
                this.navigationFrame.BackStack.RemoveAt(0);
            }
            else
            {
                this.navigationFrame.BackStack.Insert(0, new PageStackEntry(GetDestinationPageType(), null, null));
            }

            nativeStackCount = this.navigationFrame.BackStackDepth + 1;
        }
    }

    // This is used to fire NavigationFinished back to the xplat view
    // Firing NavigationFinished from Loaded is the latest reliable point
    // in time that I know of for firing `NavigationFinished`
    // Ideally we could fire it when the `NavigationTransitionInfo` is done but
    // I haven't found a way to do that
    private void OnNavigated(object sender, NavigationEventArgs e)
    {
        if (sender is not Frame frame)
        {
            return;
        }

        // If the user has inserted or removed any extra pages
        SyncBackStackToNavigationStack(this.NavigationStack);

        ProcessNavigation(frame, e);
    }

    /// <summary>
    /// Process navigation.
    /// </summary>
    /// <param name="frame">Frame</param>
    /// <param name="eventArgs">Event args</param>
    private void ProcessNavigation(UIElement frame, NavigationEventArgs eventArgs)
    {
        if (eventArgs.Content is not (Page page and FrameworkElement fe))
        {
            return;
        }

        try
        {
            Policy.Handle<Exception>()
                  .Retry(10)
                  .Execute(() => SetContent(frame, page, this.MauiContext));
        }
        catch (Exception ex)
        {
            try
            {
                Policy.Handle<Exception>()
                      .Retry(10)
                      .Execute(() =>
                       {
                           // create new context as a fallback, it will crash but then it will pick it up, it seems that it is due to invalid initial XamlRoot, this property can not be changed after it has been set
                           SetContent(frame, page, new MauiContext(this.MauiContext.Services));
                       });
            }
            catch (Exception exception)
            {
                ExceptionService.LogException(exception);

                FireNavigationFinished();

                throw;
            }
        }

        this.pendingNavigationFinished = () =>
        {
            if (page.Content is not FrameworkElement pc)
            {
                FireNavigationFinished();
            }
            else
            {
                OnLoaded(pc, FireNavigationFinished);
            }

            if (this.NavigationView is IView view && this.connected)
            {
                Arrange(view, fe);
            }
        };

        OnLoaded(fe, FirePendingNavigationFinished);
    }

    /// <summary>
    /// Sets content to page.
    /// </summary>
    /// <param name="frame">Frame</param>
    /// <param name="page">Page</param>
    /// <param name="mauiContext"></param>
    private void SetContent(UIElement frame, UserControl page, IMauiContext mauiContext)
    {
        if (this.currentPage is null)
        {
            return;
        }

        frame.XamlRoot ??= this.WindowManager.RootView.XamlRoot ?? WindowStateManager.Default.GetActiveWindow()?.Content.XamlRoot;
        page.XamlRoot ??= frame.XamlRoot;

        var presenter = new ContentPresenter
        {
            HorizontalAlignment = HorizontalAlignment.Stretch,
            VerticalAlignment = VerticalAlignment.Stretch,
            XamlRoot = page.XamlRoot
        };

        var content = this.currentPage.ToPlatform(mauiContext);
        content.XamlRoot ??= presenter.XamlRoot;

        presenter.Content = content;
        page.Content = presenter;
    }

    private void FireNavigationFinished()
    {
        this.pendingNavigationFinished = null;
        this.NavigationView?.NavigationFinished(this.NavigationStack);
    }

    private void FirePendingNavigationFinished()
    {
        Interlocked.Exchange(ref this.pendingNavigationFinished, null)?.Invoke();
    }

    private static bool IsLoaded(FrameworkElement? frameworkElement)
    {
        if (frameworkElement == null)
        {
            return false;
        }

        return frameworkElement.IsLoaded;
    }

    private static IDisposable OnLoaded(FrameworkElement? frameworkElement, Action action)
    {
        if (IsLoaded(frameworkElement))
        {
            action();

            return new ActionDisposable(() => { });
        }

        RoutedEventHandler? routedEventHandler = null;

        var disposable = new ActionDisposable(() =>
        {
            if (routedEventHandler != null)
            {
                frameworkElement!.Loaded -= routedEventHandler;
            }
        });

        routedEventHandler = (_, __) =>
        {
            disposable.Dispose();
            action();
        };

        frameworkElement!.Loaded += routedEventHandler;

        return disposable;
    }

    private static void Arrange(IView view, FrameworkElement frameworkElement)
    {
        var rect = new Rect(0, 0, frameworkElement.ActualWidth, frameworkElement.ActualHeight);

        if (!view.Frame.Equals(rect))
        {
            view.Arrange(rect);
        }
    }

    private sealed class ActionDisposable : IDisposable
    {
        private volatile Action? action;

        public ActionDisposable(Action action)
        {
            this.action = action;
        }

        public void Dispose()
        {
            Interlocked.Exchange(ref this.action, null)?.Invoke();
        }
    }
}

}`

To use this handler, register it builder.ConfigureMauiHandlers(handlers => handlers.AddHandler<NavigationPage, ExtendedNavigationViewHandler>()); If there are others just chain the call. It was better than before but we have kept getting crashes where VS debugging did not help at all, it would just show the COMException without relevant stacktrace even if we have the pdbs copied to the app and can debug external or native code, so the WinDbg was used to see what is going on. We found out about this https://github.com/microsoft/microsoft-ui-xaml/issues/9070 that would fast kill the process without any chance of recovery. So the workaround is not to use the text services at all until the issue in WinUI3 gets fixed. To disable them use this and call it somewhere during the maui startup.

`///

/// Delete after this is done https://github.com/microsoft/microsoft-ui-xaml/issues/9070 /// Default for and in WinUI is true and for MAUI it also defaults to true. /// private static void DisableTextServices() { // the discarded action calls UpdateIsSpellCheckEnabled but to protect ourselves from future modification in that corresponding action we call it manually EditorHandler.Mapper.ModifyMapping(nameof(IEditor.IsSpellCheckEnabled), (handler, editor, _) => { ((InputView)editor).IsSpellCheckEnabled = false; ((InputView)editor).IsTextPredictionEnabled = false; handler.PlatformView?.UpdateIsSpellCheckEnabled(editor); });

EditorHandler.Mapper.ModifyMapping(nameof(IEditor.IsTextPredictionEnabled), (handler, editor, _) =>
{
    ((InputView)editor).IsSpellCheckEnabled = false;
    ((InputView)editor).IsTextPredictionEnabled = false;
    handler.PlatformView?.UpdateIsTextPredictionEnabled(editor);
});

EntryHandler.Mapper.ModifyMapping(nameof(IEntry.IsSpellCheckEnabled), (handler, editor, _) =>
{
    ((InputView)editor).IsSpellCheckEnabled = false;
    ((InputView)editor).IsTextPredictionEnabled = false;
    handler.PlatformView?.UpdateIsSpellCheckEnabled(editor);
});

EntryHandler.Mapper.ModifyMapping(nameof(IEntry.IsTextPredictionEnabled), (handler, editor, _) =>
{
    ((InputView)editor).IsSpellCheckEnabled = false;
    ((InputView)editor).IsTextPredictionEnabled = false;
    handler.PlatformView?.UpdateIsTextPredictionEnabled(editor);
});

SearchBarHandler.Mapper.ModifyMapping(nameof(ISearchBar.IsSpellCheckEnabled), (handler, editor, _) =>
{
    ((InputView)editor).IsSpellCheckEnabled = false;
    ((InputView)editor).IsTextPredictionEnabled = false;
    handler.PlatformView?.UpdateIsSpellCheckEnabled(editor);
});

SearchBarHandler.Mapper.ModifyMapping(nameof(ISearchBar.IsTextPredictionEnabled), (handler, editor, _) =>
{
    ((InputView)editor).IsSpellCheckEnabled = false;
    ((InputView)editor).IsTextPredictionEnabled = false;
    handler.PlatformView?.UpdateIsTextPredictionEnabled(editor);
});

}`

With these two in place the random crashes are gone. But we still get some crashes from our customers where the stacktrace is just COMException without anything relevant to pinpoint the crash place. We suspect that it is due to some memory leaks from CsWinRT, WinUI3 and MAUI but we are not sure because we can not reproduce these crashes in our environment even with restricted VMs.

IvanStupak commented 3 months ago

@qjustfeelitp thanks for your workaround! We also struggled with this issue and implemented something similar. But let's be honest it is terrible that we have to do something like that :(

Could you please elaborate on this: it seems that it is due to invalid initial XamlRoot, this property can not be changed after it has been set

If I understood correctly, you had this issue even during initial navigation? Because our case is mostly bounded to back navigation and we didn't have to set XamlRoot again and use platform view with new MauiContext. Just re-setting presenter's content solved the issue. Maybe we missed something crucial here?

qjustfeelitp commented 3 months ago

I came up with this workaround 6 months ago and if I remember correctly I put it there only as a fallback if the first retry group fails and setting the new MauiContext helped.

The crashes are bound to back navigation but sometimes it also crashes after navigating back and to some other place.

Yes, it is not superb having to dig in Maui and look for workarounds, we have quite a lot of them, especially for WinUI3.

Foda commented 2 months ago

I'm having a bit of difficulty reproducing this, even with automated tooling. Sorry -- do y'all have a better example?

ARLasersoft commented 2 months ago

Hi @Foda

I am a colleague of Davide who will be away for a few days. We found and reproduced the error together. I'll answer for him.

I tried to launch the example again and I still get the error.

I did some tests with workloads for maui-windows for 8.0.7 and 8.0.72 on different machines (Win 10 and 11), debug and release: . maui-windows 8.0.7/8.0.100 VS 17.9.34723.18, VS 17.9.34723.18 . maui-windows 8.0.72/8.0.100 SDK 8.0.400, VS 17.11.35222.181

Used TinyTask for automating navigation (I used 2x speed). The only thing that seems relevant is that on a performance PC (I tested with an i7) it happens more rarely.

I get same exception. What information might be useful for you to reproduce it?

Foda commented 1 month ago

@ARLasersoft I'm pretty much unable to reproduce this on my machine without spending huge amounts of time on it. I've clicked "navigate to page 2" then back to the main page >1000 times without a crash. I also let the automated tool run for >20 mins without it occurring.

Then, I randomly clicked a few times and it triggered. But since then I've been unable to reproduce it over the past 2 days... could you try and reproduce this in a plain WinUI app using the Frame control? Or try and get a more reliable way to reproduce this on a fast machine?

qjustfeelitp commented 1 month ago

@Foda Here is my repro https://github.com/qjustfeelitp/maui-22790-repro here is the memory dump https://fileport.io/3mCwzcmFgatG and corresponding call stack https://github.com/qjustfeelitp/maui-22790-repro/blob/main/stack.txt

It's just a simple app as I could not get you our business app which is far more complex and this issue appeared more frequently, if you cannot reproduce it, relaunch the app and try again.

Do you think this is enough?

IvanStupak commented 1 month ago

@ARLasersoft I'm pretty much unable to reproduce this on my machine without spending huge amounts of time on it. I've clicked "navigate to page 2" then back to the main page >1000 times without a crash. I also let the automated tool run for >20 mins without it occurring.

Then, I randomly clicked a few times and it triggered. But since then I've been unable to reproduce it over the past 2 days... could you try and reproduce this in a plain WinUI app using the Frame control? Or try and get a more reliable way to reproduce this on a fast machine?

I believe it's not possible to reproduce this issue in a plain WinUI using Frame control, just because exception occurs when MAUI's StackNavigationManager tries to set content into the page presenter (and it's a good question what was the intense to implement navigation in this way): https://github.com/dotnet/maui/blob/049ec597534a77c0c57a0207c856453387f1f54b/src/Core/src/Platform/Windows/StackNavigationManager.cs#L183 Plain WinUI navigation approach with Frame control doesn't need this manipulation and works differently.

PureWeen commented 1 month ago

@IvanStupak do you have an example of implementing it a different way?

rogerbriggen-securiton commented 1 month ago

Our app crashes also every day because of this bug on Windows by just simple navigating between pages and the problem is there since the launch of MAUI

Yannikk1996 commented 1 month ago

We encounter this issue occasionally as well, and it can be quite frustrating.

ARLasersoft commented 1 month ago

If it can be useful information, another way to mitigate the frequency of error (please note, mitigate, not avoid) is to place a little delay before navigating:

Task.Delay(300) or Task.Sleep()

Catching the exception is possibile, but at that point navigation no longer works and you need to kill and restart app.

PureWeen commented 1 month ago

If anyone can provide a more consistent repro, exception, or possibly a stack dump when the exception happens that would be helpful.

Adan0s commented 1 month ago

Can't really share my repo, but will try to isolate it in a new repo in the coming days.

Normally it takes between 5-20 navigations back and forth between pages but it will definitely crash after some time. We're using Sentry (and AppCenter) to log our crashes in prod and all windows devices (does not matter if win10 or win11) have daily crashes with the same exception.

In debug two unhandled exceptions will occour before the app crashes:

Microsoft.UI.Xaml.Controls.Frame.NavigationFailed was unhandled.

> MyApp.dll! MyApp.WinUI.App.InitializeComponent.AnonymousMethod__3_2(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e) Line 75 C# Microsoft.WinUI.dll!WinRT._EventSource_global__Microsoft_UI_Xaml_UnhandledExceptionEventHandler.EventState.GetEventInvoke.AnonymousMethod__1_0(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e) Unknown Microsoft.WinUI.dll!ABI.Microsoft.UI.Xaml.UnhandledExceptionEventHandler.Do_Abi_Invoke(nint thisPtr, nint sender, nint e) Unknown [Native to Managed Transition] [Managed to Native Transition] Microsoft.WinUI.dll!ABI.Microsoft.UI.Xaml.Controls.IFrameMethods.GoBack(WinRT.IObjectReference _obj, Microsoft.UI.Xaml.Media.Animation.NavigationTransitionInfo transitionInfoOverride) Unknown Microsoft.WinUI.dll!Microsoft.UI.Xaml.Controls.Frame.GoBack(Microsoft.UI.Xaml.Media.Animation.NavigationTransitionInfo transitionInfoOverride) Unknown Microsoft.Maui.dll!Microsoft.Maui.Platform.StackNavigationManager.NavigateTo(Microsoft.Maui.NavigationRequest args) Unknown Microsoft.Maui.Controls.dll!Microsoft.Maui.Controls.Handlers.ShellSectionHandler.RequestNavigation(Microsoft.Maui.Controls.Handlers.ShellSectionHandler handler, Microsoft.Maui.IStackNavigation view, object arg3) Unknown Microsoft.Maui.dll!Microsoft.Maui.CommandMapper.InvokeCore(string key, Microsoft.Maui.IElementHandler viewHandler, Microsoft.Maui.IElement virtualView, object args) Unknown Microsoft.Maui.dll!Microsoft.Maui.Handlers.ElementHandler.Invoke(string command, object args) Unknown Microsoft.Maui.Controls.dll!Microsoft.Maui.Controls.ShellSection.Microsoft.Maui.IStackNavigation.RequestNavigation(Microsoft.Maui.NavigationRequest eventArgs) Unknown Microsoft.Maui.Controls.dll!Microsoft.Maui.Controls.Handlers.ShellSectionHandler.SyncNavigationStack(bool animated, Microsoft.Maui.Controls.Internals.NavigationRequestedEventArgs e) Unknown Microsoft.Maui.Controls.dll!Microsoft.Maui.Controls.Handlers.ShellSectionHandler.OnNavigationRequested(object sender, Microsoft.Maui.Controls.Internals.NavigationRequestedEventArgs e) Unknown Microsoft.Maui.Controls.dll!Microsoft.Maui.Controls.ShellSection.InvokeNavigationRequest(Microsoft.Maui.Controls.Internals.NavigationRequestedEventArgs args) Unknown Microsoft.Maui.Controls.dll!Microsoft.Maui.Controls.ShellSection.OnPopAsync(bool animated) Unknown Microsoft.Maui.Controls.dll!Microsoft.Maui.Controls.ShellSection.GoToAsync(Microsoft.Maui.Controls.ShellNavigationRequest request, Microsoft.Maui.Controls.ShellRouteParameters queryData, System.IServiceProvider services, bool? animate, bool isRelativePopping) Unknown Microsoft.Maui.Controls.dll!Microsoft.Maui.Controls.ShellNavigationManager.GoToAsync.AnonymousMethod__1() Unknown Microsoft.Maui.dll!Microsoft.Maui.Dispatching.DispatcherExtensions.DispatchAsync.AnonymousMethod__0() Unknown Microsoft.Maui.dll!Microsoft.Maui.Dispatching.DispatcherExtensions.DispatchAsync.AnonymousMethod__0() Unknown Microsoft.InteractiveExperiences.Projection.dll!ABI.Microsoft.UI.Dispatching.DispatcherQueueHandler.Do_Abi_Invoke(nint thisPtr) Unknown [Native to Managed Transition] [Managed to Native Transition] Microsoft.WinUI.dll!ABI.Microsoft.UI.Xaml.IApplicationStaticsMethods.Start(WinRT.IObjectReference _obj, Microsoft.UI.Xaml.ApplicationInitializationCallback callback) Unknown Microsoft.WinUI.dll!Microsoft.UI.Xaml.Application.Start(Microsoft.UI.Xaml.ApplicationInitializationCallback callback) Unknown MyApp.dll! MyApp.WinUI.Program.Main(string[] args) Line 32 C#

Second exception after that:

System.Runtime.InteropServices.COMException

> MyApp.dll! MyApp.WinUI.App.InitializeComponent.AnonymousMethod__3_2(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e) Line 75 C# Microsoft.WinUI.dll!WinRT._EventSource_global__Microsoft_UI_Xaml_UnhandledExceptionEventHandler.EventState.GetEventInvoke.AnonymousMethod__1_0(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e) Unknown Microsoft.WinUI.dll!ABI.Microsoft.UI.Xaml.UnhandledExceptionEventHandler.Do_Abi_Invoke(nint thisPtr, nint sender, nint e) Unknown [Native to Managed Transition] [Managed to Native Transition] WinRT.Runtime.dll!WinRT.ExceptionHelpers.ReportUnhandledError(System.Exception ex) Unknown Microsoft.InteractiveExperiences.Projection.dll!Microsoft.UI.Dispatching.DispatcherQueueSynchronizationContext.Post.AnonymousMethod__0() Unknown Microsoft.InteractiveExperiences.Projection.dll!ABI.Microsoft.UI.Dispatching.DispatcherQueueHandler.Do_Abi_Invoke(nint thisPtr) Unknown [Native to Managed Transition] [Managed to Native Transition] Microsoft.WinUI.dll!ABI.Microsoft.UI.Xaml.IApplicationStaticsMethods.Start(WinRT.IObjectReference _obj, Microsoft.UI.Xaml.ApplicationInitializationCallback callback) Unknown Microsoft.WinUI.dll!Microsoft.UI.Xaml.Application.Start(Microsoft.UI.Xaml.ApplicationInitializationCallback callback) Unknown MyApp.dll! MyApp.WinUI.Program.Main(string[] args) Line 32 C#

Then the app will crash/close.

I have saved two memory dumps but they are pretty big (each one 600mb) and I'm not too keen to share them in public, as they'll probably contain some internal info.

qjustfeelitp commented 1 month ago

@PureWeen I thought that I already provided enough information even with a workaround. Here is a stacktrace from visual studio https://github.com/qjustfeelitp/maui-22790-repro/blob/main/visualStudioStack.txt This one is from WinDbg https://github.com/qjustfeelitp/maui-22790-repro/blob/main/stack.txt

Here is memory dump https://fileport.io/3mCwzcmFgatG

I updated the code to automate the navigation https://github.com/qjustfeelitp/maui-22790-repro If you want to try it with my dumb workaround using retries, enable it here https://github.com/qjustfeelitp/maui-22790-repro/blob/48a59c0ff211d2cf9359ceab450e39927e524df0/src/Maui22790/MauiProgram.cs#L9

I don't think that it is tied to your machine, mine is beefy enough: Procesor 12th Gen Intel(R) Core(TM) i9-12900 with 64 gigs of RAM

If you need more information, please don't hesitate to be specific.

Foda commented 1 month ago

@PureWeen I thought that I already provided enough information even with a workaround. Here is a stacktrace from visual studio https://github.com/qjustfeelitp/maui-22790-repro/blob/main/visualStudioStack.txt This one is from WinDbg https://github.com/qjustfeelitp/maui-22790-repro/blob/main/stack.txt

Here is memory dump https://fileport.io/3mCwzcmFgatG

I updated the code to automate the navigation https://github.com/qjustfeelitp/maui-22790-repro If you want to try it with my dumb workaround using retries, enable it here https://github.com/qjustfeelitp/maui-22790-repro/blob/48a59c0ff211d2cf9359ceab450e39927e524df0/src/Maui22790/MauiProgram.cs#L9

I don't think that it is tied to your machine, mine is beefy enough: Procesor 12th Gen Intel(R) Core(TM) i9-12900 with 64 gigs of RAM

If you need more information, please don't hesitate to be specific.

Looks like the dmp file was taken down -- could you please email it to me (the exception is a stowed exception, so it's not possible to tell what the "real" one is from the stack trace...)? mikecorsaro at microsoft. Thanks!

Testing your automated example -- it doesn't actually seem to crash on the latest "main" branch. I don't think anything was fixed related to it but have you had the chance to try it there?

bronteq commented 1 month ago

This issue just happened also to me, the Windows app uses Maui 8.0.40 and I was doing a back navigation with await Shell.Current.GoToAsync("..");

There is a first unhandled exception with empty text in Exception field and the following text in Message field: Microsoft.UI.Xaml.Controls.Frame.NavigationFailed was unhandled.

Then a second exception is thrown:

System.Runtime.InteropServices.COMException (0x80004005)
   at WinRT.ExceptionHelpers.<ThrowExceptionForHR>g__Throw|39_0(Int32 hr)
   at ABI.Microsoft.UI.Xaml.Controls.IFrameMethods.GoBack(IObjectReference _obj, NavigationTransitionInfo transitionInfoOverride)
   at Microsoft.UI.Xaml.Controls.Frame.GoBack(NavigationTransitionInfo transitionInfoOverride)
   at Microsoft.Maui.Platform.StackNavigationManager.NavigateTo(NavigationRequest args)
   at Microsoft.Maui.Controls.Handlers.ShellSectionHandler.RequestNavigation(ShellSectionHandler handler, IStackNavigation view, Object arg3)
   at Microsoft.Maui.CommandMapper.InvokeCore(String key, IElementHandler viewHandler, IElement virtualView, Object args)
   at Microsoft.Maui.Handlers.ElementHandler.Invoke(String command, Object args)
   at Microsoft.Maui.Controls.ShellSection.Microsoft.Maui.IStackNavigation.RequestNavigation(NavigationRequest eventArgs)
   at Microsoft.Maui.Controls.Handlers.ShellSectionHandler.SyncNavigationStack(Boolean animated, NavigationRequestedEventArgs e)
   at Microsoft.Maui.Controls.Handlers.ShellSectionHandler.OnNavigationRequested(Object sender, NavigationRequestedEventArgs e)
   at Microsoft.Maui.Controls.ShellSection.InvokeNavigationRequest(NavigationRequestedEventArgs args)
   at Microsoft.Maui.Controls.ShellSection.OnPopAsync(Boolean animated)
   at Microsoft.Maui.Controls.ShellSection.GoToAsync(ShellNavigationRequest request, ShellRouteParameters queryData, IServiceProvider services, Nullable`1 animate, Boolean isRelativePopping)
   at Microsoft.Maui.Dispatching.DispatcherExtensions.<>c__DisplayClass3_0.<<DispatchAsync>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.Maui.Dispatching.DispatcherExtensions.<>c__DisplayClass2_0`1.<<DispatchAsync>b__0>d.MoveNext()
--- End of stack trace from previous location ---
   at Microsoft.Maui.Controls.ShellNavigationManager.GoToAsync(ShellNavigationParameters shellNavigationParameters, ShellNavigationRequest navigationRequest)
   at xx.xx.xx.xx()

After that, the same back navigation does not work anymore, but it's possible to successfully navigate to another page by clicking a Shell FlyoutItem, then the navigation seems to restart working as before.

Foda commented 3 weeks ago

Looks like this might be the actual cause: https://github.com/microsoft/CsWinRT/issues/1834