Search code examples
mauiasp.net-core-signalr.net-maui.shell

SignalR and .Net Maui - Shell.Current.GoToAsync Issue


I made a .Net Maui app and I tried to make an online version of it using SignalR.
The connection is established successfully and I get an answer from the server and the Shell.Current.GoToAsync command is executed but the page is not changing at all.
If I use the same command outside the connection the page changes as expected.
I believe that the cause of this is that it is not running on the main thread but I need to navigate to another page when I get the correct response from the SignalR server.
Through debugging I can see that the other page initialization is executed but from another thread.
Below is a much simpler version of the code showing only what is required for this issue.

[ObservableProperty]
private string connectionID;

[ObservableProperty]
private string word;
    
private HubConnection _connection;

[RelayCommand]
async Task JoinGame()
{
    _connection = new HubConnectionBuilder()
    .WithUrl($"{baseUrl}/Hub")
    .Build();

    _connection.On<string, string, string>("CheckIfConnectionMatchAnswer", async (connectionID, answer, word) =>
    {
        if (ConnectionID == connectionID && answer == "True")
        {
            Word = word;
            await Shell.Current.GoToAsync(nameof(GamePage));
        }
    });
    await _connection.StartAsync();
    await _connection.InvokeCoreAsync("CheckConnectionID", args: new[] { ConnectionID });
}

I expected to navigate to another page but that didn't happen.


Solution

  • The solution was to use MainThread.BeginInvokeOnMainThread(action); to trigger the action with the UI thread and update the page. Please note that this works as well with updating UI elements were I was struggling with the same issue once again.

    Microsoft - Run code on the main UI thread .Net Maui