Reputation: 465
I have a function which calls a server to update a database and I wait around for it to complete before returning the result :
public async Task<int> CarryOutPreRegisterDevice(string emailAddress)
{
int intRet=-1;
Task<int> tski = PreRegisterDevice(emailAddress);
intRet = await tski;
return intRet;
}
What I would like to do is display a progressdialog whilst this is happening. However, as soon as I wrap the await line in a progress dialog it allows the original thread to run on and return intRet before the awaited task has completed.
public async Task<int> CarryOutPreRegisterDevice(string emailAddress)
{
int intRet = -1;
Task<int> tski = PreRegisterDevice(emailAddress);
ProgressDialog progressDialog;
progressDialog = ProgressDialog.Show(AppGlobals.CurrentActivity, "", "Sending....", true);
progressDialog.SetProgressStyle(ProgressDialogStyle.Spinner);
new Thread(new ThreadStart(async delegate
{
intRet = await tski;
progressDialog.Dismiss();
})).Start();
return intRet;
}
Is there a better way of structuring this so that the return line does not get executed before the task has completed.
Thanks.
Upvotes: 0
Views: 1252
Reputation: 15151
Not sure why you have created a thread, that defeats the purpose of tasks. If you want to show an spinner while the long task is running just await it after showing the progressdialog:
public async Task<int> CarryOutPreRegisterDevice(string emailAddress)
{
ProgressDialog progressDialog;
progressDialog = ProgressDialog.Show(AppGlobals.CurrentActivity, "", "Sending....", true);
progressDialog.SetProgressStyle(ProgressDialogStyle.Spinner);
var intRet = await PreRegisterDevice(emailAddress);
progressDialog.Dismiss();
return intRet;
}
Upvotes: 1