How to navigate to another page when not on UI thread?

Paul Hollyer 0 Reputation points
2023-03-28T16:04:58.8866667+00:00

I'm building a mobile and desktop app with Maui + MauiReactor that communicates with my server over Websockets. I have this working fine.

My problem is that if I try to Navigate to another page when I receive a Websocket reply:

await Navigation.pushAsync<NewPage>();

I get the following error:

UIKit Consistency error: you are calling a UIKit method that can only be invoked from the UI thread.

I understand why this happening, just not how best to handle it.

I can display a button after the message has been received, which the user can click to navigate which is obviously performing the navigaton on the UI thread due to the button click, but this feels really clunky. Is it possible to raise the process onto the UI thread so that I can programmatically navigate automatically?

My use case is as follows:

User starts the app, navigates to the sign in page, and enters credentials

Credentials get sent to my server over a websocket

Websocket reply confirms credentials and supplies a session token

Now I need to navigate to another page based on the current state of their profile settings i.e. if incomplete, go to profile page, if complete go back home. I would like this to be automatic without forcing the user to click a button to navigate.

Can anyone advise on how best to go about this?

Many thanks.

(I've just started my dotnet journey, still learning c# but enjoying every second of it, been doing FP for the last 8 yrs or so, enjoying a bit of OO again.)

Developer technologies .NET .NET MAUI
Developer technologies .NET Other
Developer technologies C#
{count} votes

1 answer

Sort by: Most helpful
  1. Paul Hollyer 0 Reputation points
    2023-03-29T08:08:41.8566667+00:00

    Seems like a Maui thing according to Adolfo

    The following works:

    MauiControls.Application.Current?.Dispatcher.Dispatch(() => Navigation.PopAsync());

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.