Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to dynamically change Button's text causes system.runtime.interopservices.comexception in .NET MAUI app

Well, the situation is that I’m going to use Timer in a simple quiz MAUI app. And I wanted to show timer changing numbers as a Button text. It works well on WinForms app, but on MAUI it caused system.runtime.interopservices.comexception 0x8001010e rpc_e_wrong_thread exception.

So, is it possible to do that and if yes how to?
Here is a method where the exception occures:

private void Timer_Tick(object sender, EventArgs e)
    {
        timePerQuestion--;

        //next line causes an exception
        sendAnswerButton.Text = $"Send ({timePerQuestion} {secondsSpelling(timePerQuestion)})";
        if (timePerQuestion == 0)
        {
            timer.Stop();
            SendAnswer_Clicked(sender, new EventArgs());
        }
    }

I’m new to .NET MAUI and have no clue how to deal with multithreading in it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to update the UI, you need to run the code on the main thread. So you can try to use the BeginInvokeOnMainThread, such as:

MainThread.BeginInvokeOnMainThread(()=>
   {
     sendAnswerButton.Text = $"Send ({timePerQuestion} {secondsSpelling(timePerQuestion)})";
   });

For more information about the Main thread, you can refert to Which is better MainThread.Being/InvokeVS Dispatcher.Dispatch.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading