How to use RunOnUIThread () in Xamarin Android

I would like to run this statement after getting the result in the OStateUserId object.

details.Text = OStateUserID.name + "\n" + OStateUserID.population);

 bStateuserID.Click += async delegate { details.Text=" "; Guid x = new Guid("33F8A8D5-0DF2-47A0-9C79-002351A95F88"); state OStateUserID =(state) await obj.GetStateByUserId(x.ToString()); details.Text = OStateUserID.name + "\n" + OStateUserID.population); }; 

GetStateByUserId() method returns a class State object.

It is executed asynchronously. After the operation is completed, I would like to assign the name and population of the TextView data.

How can I use RunOnUIThread() in this case?

+6
source share
2 answers

You do not need.

In this code you sent:

 bStateuserID.Click += async delegate { details.Text=" "; Guid x = new Guid("33F8A8D5-0DF2-47A0-9C79-002351A95F88"); state OStateUserID =(state) await obj.GetStateByUserId(x.ToString()); details.Text = OStateUserID.name + "\n" + OStateUserID.population); }; 

Line

 details.Text = OStateUserID.name + "\n" + OStateUserID.population); 

already running in the user interface thread.

I have an async intro on my blog that explains this behavior.

+4
source

I'm not sure how you could miss this, since you have the correct function name. In any case, you can do this using the lambda expression:

 Activity.RunOnUiThread(() => { details.Text = OStateUserID.name + "\n" + OStateUserID.population; }); 

Or you can create a method for it

 Activity.RunOnUiThread(Action); private void Action() { details.Text = OStateUserID.name + "\n" + OStateUserID.population; } 

In the latter case, you will need to store the variables in private fields, if this is not the case. In the first case, it will work if the variables are in the same area as the call to RunOnUiThread.

+10
source

All Articles