Robert
Robert

Reputation: 13

.Net MAUI: Exception TargetInvocation on DisplayAlert

I'm currently working on my first .NET MAUI application, and I have successfully used DisplayAlert messages on other pages without any issues. However, I encountered a problem when trying to display a DisplayAlert message within the AppShell, where I have set up SignalR using the code provided. When I attempt to include the message in a DisplayAlert, it throws an exception. On the other hand, if I simply use a regular label to display the message, it works fine.

 private readonly HubConnection _hubConnection;
    private string baseUrl = "https:/";


    public AppShell()
    {
        InitializeComponent();

        // Disable back button for a specific page
        NavigationPage.SetHasBackButton(this, false);

        _hubConnection = new HubConnectionBuilder().WithUrl($"{baseUrl}/notificationhub").Build();
        _hubConnection.On<Notification>("NewCallNotificationReceived", (notify) =>
        {
            ShowPopup(notify.Message);
        });

        Task.Run(() =>
        {
            Dispatcher.Dispatch(async () =>
            {
                await _hubConnection.StartAsync();
            });
        });
    }
    private async void ShowPopup(string message)
    {
        await DisplayAlert("Title", message, "OK");
    }

Upvotes: 0

Views: 695

Answers (1)

vishnu t
vishnu t

Reputation: 21

run it in main thread like the sample below:

   MainThread.BeginInvokeOnMainThread(async () =>
        {
            await DisplayAlert("Alert", "You have been alerted", "OK");
        });

Upvotes: 0

Related Questions