I'm starting my adventure with mobile developing and already faced a problem. I know in WPF I would use BackgroundWorker
to update the UI, but how does it work with Android using Xamarin?
I've found many advises but none of these worked for me. The code below won't change the text while the rest is being executed, it just awaits and performs all at once, which isn't what I want.
private void Btn_Click(object sender, System.EventArgs e)
{
RunOnUiThread(() => txt.Text = "Connecting...");
//txt.Text = sql.testConnectionWithResult();
if (sql.testConnection())
{
txt.Text = "Connected";
load();
}
else
txt.Text = "SQL Connection error";
}
There are many ways to do this, but in the form of your example code:
FYI: There are some great libraries that can help create a reactive user experience, with
ReactiveUI
being at the top of my list as it also is a MVVM framework...Like WPF Xamarin supports Async/Await too!
https://developer.xamarin.com/guides/cross-platform/advanced/async_support_overview/
https://developer.xamarin.com/samples/mobile/AsyncAwait/
Here your action comes from a button click action, so you don't need to use RunOnUiThread because you are ready working on this one.
If I understand correctly your code it should look like this :
The code inside Task.Run will be called asynchronously without blocking the ui. You can use await word inside the Task.Run if you need to wait for specific work before update UI elements.