What is the correct way to use Runonuithread() in Xamarin.Android?

Asked

Viewed 324 times

4

When I need to update a field on the UI, I need to run this code on the UI thread?

For example: I have to change my layout Activity.

The code I’m using is this:

RunOnUiThread(() =>
{
    _layoutBlurred.Visibility = ViewStates.Visible;
    _layoutBlurred.Background = image;
    _layoutContent.Visibility = ViewStates.Invisible;
    _listViewScheduling.Enabled = false;
});

Or even a simple text exchange of a Textview:

_txtStatus.Text = GetString(Resource.String.app_online);

It is necessary to use the RunOnUiThread() in these cases or not?

  • You have to use Runonuithread, but I think there is a smarter concept for this which is Asynctasks, after a look at this link: http://www.devmedia.com.br/asynctask-workwith asynchronous tasks/29823

  • There is another question that talks more about Asynctask, I think it adapts more in this your scenario! https://answall.com/questions/68056/thread-ou-asynctask-quando-e-qual-devo-usar

2 answers

2

Yes, it is necessary.

Components declared and displayed in the UI live in the UI and are operating in the thread ui.

Accessing these components from another thread would violate thread-Safety. That is why this method is necessary.

There’s others cases that seem like that cause the need to use the method RunOnUiThread, but there really isn’t that need

Example:

btActivate.Click += async delegate 
{
    bool x = await Foo.ActivateAsync();
    txtResult.Text = x ? "Successful" : "Failed";
};

In this case, the delegate asynchronous attributed to the event click button is already in the UI thread, because it is invoked in the thread of the control it was associated with. And when the asynchronous method ActivateAsync returns, it is summarized in the UI thread, and best of all is that it does not lock the UI thread while it runs, as it is expected asynchronously with the keyword await.

-2

Currently use Xamarin Essentials

MainThread.BeginInvokeOnMainThread(() =>
{
            
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.