.net Maui Comexeption raised when Connection lost

Im currently working on a maui project which I use for the ui of my raspberry pi.

It often disconnects and therefore I implemented a ConnectionLost event where it should clean the ui and display a alert so i can see whenever it disconnects and just connect again.

However when i try to change the ui contents I get a ComException with the message

The application called an interface that was marshalled for a different thread (0x8001010E (RPC_E_WRONG_THREAD))’

Here is the C# Method

private async void OnConnectionLost()
{
     ReaderBtn.IsEnabled = false;
     PriorityBtn.IsEnabled = false;
     SetIp("Not connected");
     await DisplayAlert("Error","Connection Lost", "OK");    
}

 public void SetIp(string ip)
 {
     idStr.Text = ip;
     deviceStr.Text = "";
     nrStr.Text = "";
     UpdateIpColor();
 }

What would I have to add so the Exception will not come up?

>Solution :

The application called an interface that was marshalled for a different thread (0x8001010E (RPC_E_WRONG_THREAD))’

It means that you are trying to update UI from a different (not UI) thread. For example, set text to Label or something else.

This method (if it is called on connection lost) needs to be called from MainThread.

private async void OnConnectionLost()
{
    MainThread.BeginInvokeOnMainThread(() =>
    {
       // Code to run on the main thread
       ReaderBtn.IsEnabled = false;
       PriorityBtn.IsEnabled = false;
       SetIp("Not connected");
       await DisplayAlert("Error","Connection Lost", "OK");    

     });
}

Leave a Reply