Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WinRt exception when page navigated #22790

Closed
davide-cavallini opened this issue Jun 3, 2024 · 26 comments · Fixed by #25740
Closed

WinRt exception when page navigated #22790

davide-cavallini opened this issue Jun 3, 2024 · 26 comments · Fixed by #25740
Assignees
Labels
area-controls-shell Shell Navigation, Routes, Tabs, Flyout area-navigation NavigationPage fixed-in-9.0.21 p/1 Work that is important, and has been scheduled for release in this or an upcoming sprint partner/cat 😻 this is an issue that impacts one of our partners or a customer our advisory team is engaged with platform/windows 🪟 s/needs-attention Issue has more information and needs another look s/triaged Issue has been reviewed s/verified Verified / Reproducible Issue ready for Engineering Triage t/bug Something isn't working
Milestone

Comments

@davide-cavallini
Copy link

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()
@davide-cavallini davide-cavallini added the t/bug Something isn't working label Jun 3, 2024
Copy link
Contributor

github-actions bot commented Jun 3, 2024

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.

@jsuarezruiz jsuarezruiz added platform/windows 🪟 area-navigation NavigationPage area-controls-shell Shell Navigation, Routes, Tabs, Flyout labels Jun 3, 2024
@jaosnz-rep
Copy link

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.

@jsuarezruiz jsuarezruiz added the s/needs-info Issue needs more info from the author label Jun 4, 2024
@dotnet-policy-service dotnet-policy-service bot added s/needs-attention Issue has more information and needs another look and removed s/needs-info Issue needs more info from the author labels Jun 4, 2024
@davide-cavallini
Copy link
Author

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

@jaosnz-rep
Copy link

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

@jaosnz-rep jaosnz-rep added s/verified Verified / Reproducible Issue ready for Engineering Triage s/triaged Issue has been reviewed labels Jun 4, 2024
@jsuarezruiz jsuarezruiz removed the s/needs-attention Issue has more information and needs another look label Jun 6, 2024
@jsuarezruiz jsuarezruiz added this to the Backlog milestone Jun 6, 2024
@PureWeen PureWeen modified the milestones: Backlog, .NET 8 SR8 Jul 2, 2024
@PureWeen PureWeen added the p/1 Work that is important, and has been scheduled for release in this or an upcoming sprint label Jul 2, 2024
@samhouts samhouts removed s/verified Verified / Reproducible Issue ready for Engineering Triage s/triaged Issue has been reviewed labels Jul 3, 2024
@Adan0s
Copy link

Adan0s commented Jul 10, 2024

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.

@samhouts samhouts added s/verified Verified / Reproducible Issue ready for Engineering Triage s/triaged Issue has been reviewed labels Jul 10, 2024
@qjustfeelitp
Copy link

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 microsoft/microsoft-ui-xaml#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 microsoft/microsoft-ui-xaml#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.

@PureWeen PureWeen modified the milestones: .NET 8 SR8, .NET 8 SR9 Jul 30, 2024
@IvanStupak
Copy link

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

@Yannikk1996
Copy link

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

@ARLasersoft
Copy link

ARLasersoft commented Sep 17, 2024

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
Copy link
Member

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

@PureWeen PureWeen moved this from Won't Make SR9 to In Progress in MAUI SDK Ongoing Sep 17, 2024
@Adan0s
Copy link

Adan0s commented Sep 18, 2024

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
Copy link

@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
Copy link
Member

Foda commented Sep 23, 2024

@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
Copy link

bronteq commented Sep 24, 2024

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
Copy link
Member

Foda commented Oct 17, 2024

Looks like this might be the actual cause: microsoft/CsWinRT#1834

@MitchBomcanhao
Copy link

MitchBomcanhao commented Nov 15, 2024

We've started getting loads of failures when doing some specific navigation events in our app after upgrading to .net9.
oddly enough, adding something like thread.delay(500) before calling the navigation method appeared to reduce those crashes, but this is not a suitable fix...

error we get is PlatformView cannot be null here which comes after doing stuff like Navigation.PopAsync, Navigation.PopModalAsync,Application.Current.Windows[0].Page = page, when it gets to disconnect handlers...

still failing in .net9 sr1 release

@MitchBomcanhao
Copy link

@Foda is there a CI build with these changes? if so, what is its version?

@MitchBomcanhao
Copy link

We've started getting loads of failures when doing some specific navigation events in our app after upgrading to .net9. oddly enough, adding something like thread.delay(500) before calling the navigation method appeared to reduce those crashes, but this is not a suitable fix...

error we get is PlatformView cannot be null here which comes after doing stuff like Navigation.PopAsync, Navigation.PopModalAsync,Application.Current.Windows[0].Page = page, when it gets to disconnect handlers...

still failing in .net9 sr1 release

for the sake of correctness, I can now say that the issue I mentioned above is caused by UraniumUI and its InputKit.Maui dependency, not directly related with maui. but something may have changed in maui .net9 that prompted this to start failing, as we had this package in place for a long while and only now it started failing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-controls-shell Shell Navigation, Routes, Tabs, Flyout area-navigation NavigationPage fixed-in-9.0.21 p/1 Work that is important, and has been scheduled for release in this or an upcoming sprint partner/cat 😻 this is an issue that impacts one of our partners or a customer our advisory team is engaged with platform/windows 🪟 s/needs-attention Issue has more information and needs another look s/triaged Issue has been reviewed s/verified Verified / Reproducible Issue ready for Engineering Triage t/bug Something isn't working
Projects
Status: Done
Development

Successfully merging a pull request may close this issue.