maui: WinRt exception when page navigated

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()

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 2
  • Comments: 26 (7 by maintainers)

Commits related to this issue

Most upvoted comments

@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.

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.

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.

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.

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 <see cref="ITextInput.IsSpellCheckEnabled"/> and <see cref="ITextInput.IsTextPredictionEnabled"/> 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.

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