Reputation: 24562
My intention is that when a button is pressed an activity indicator will display on the screen immediately and then a database query will happen. Once the query is completed a XAML grid is created, the activity indicator will be removed and the new XAML grid added. In practice this is all working but often the activity indicator does not show so I am wondering if I have the way I coded this wrong.
I have a button that causes an UpdateDetails method to fire:
private async Task UpdateDetails()
{
details.Children.Clear();
details.Children.Add(Helpers.Activity.Create());
var newGrid = doLongRunningDatabaseTaskandCreateXAML();
details.Children.Clear();
details.Children.Add(Helpers.Activity.Create(newGrid);
}
How I can make the activity indicator display first until the database operation has completed and then have the newGrid appear? Note that what's most important is for the activity indicator to show while the database operation and creation of newGrid is ongoing.
Upvotes: 0
Views: 76
Reputation: 16449
Well, its simple:
Make your method synchronous
Add the code that you don't want on UI thread in an async Task.Run
Task.Run(async () =>
{
//Your piece of code
}
Now when you want to update the UI just write that part of the code in MainThread
using the following
Device.BeginInvokeOnMainThread(() => { //UI updation });
Your code should look something like this:
private async Task UpdateDetails()
{
Task.Run(async () =>
{
Device.BeginInvokeOnMainThread(() => { details.Children.Clear();
details.Children.Add(Helpers.Activity.Create());});
var newGrid = await doLongRunningDatabaseTaskandCreateXAML();
Device.BeginInvokeOnMainThread(() => { details.Children.Clear();
details.Children.Add(Helpers.Activity.Create(newGrid);});
}
}
Note that if doLongRunningDatabaseTaskandCreateXAML
is of the type async task
then you do not need to use the Task.Run
method at all.
Upvotes: 1