Reputation: 35
I am building Xamarin
android app and I have a function that needs some time.
Now, I am trying to display a ProgressDialog
and execute the function.
The code below do not show the ProgressDialog
, I just see nothing. Can you please help me ?
private void BtButton_Click(object sender, System.EventArgs e)
{
ProgressDialog mDialog = new ProgressDialog(this);
mDialog.SetMessage("Loading data...");
mDialog.SetCancelable(false);
mDialog.Show();
Task t = Task.Run(() => { Foo(); });
t.Wait();
mDialog.Dismiss();
}
private void Foo()
{
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
}
}
Upvotes: 1
Views: 1080
Reputation: 12179
You are blocking the main thread by invoking t.Wait()
, more information can be found here.
Instead you can do something like this:
async void BtButton_Click(object sender, System.EventArgs e)
{
var mDialog = new ProgressDialog(this);
mDialog.SetMessage("Loading data...");
mDialog.SetCancelable(false);
mDialog.Show();
await Task.Run((() => Foo()));
// Alternatively
// await Task.Delay(10000);
mDialog.Dismiss();
}
void Foo()
{
for (int i = 0; i < 10; i++)
{
Thread.Sleep(1000);
}
}
P.S.: ProgressDialog
is deprecated in API level 26 use alternatives.
Upvotes: 1