简体   繁体   中英

Using ProgressDialog with async/wait, C# Android

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM