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

4

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

For example: I have to change the layout of my 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);

Do you need to use RunOnUiThread() in these cases or not?

    
asked by anonymous 27.07.2017 / 15:03

1 answer

2

Yes, it is necessary.

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

Accessing these components from another thread would violate thread-safety . This is why this method is necessary.

There are others cases that seem to cause the need to use RunOnUiThread method,

Example:

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

In this case, the asynchronous delegate legated assigned to the click of the 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 is running because it is expected asynchronously with the keyword await . / p>     

15.09.2017 / 16:35