使用ProgressDialog和异步/等待,C#Android

时间:2017-05-04 15:25:46

标签: c# android asynchronous progressdialog

我有一个函数调用服务器来更新数据库,我等待它完成后再返回结果:

public async Task<int> CarryOutPreRegisterDevice(string emailAddress)
{
    int intRet=-1;
    Task<int> tski = PreRegisterDevice(emailAddress);

    intRet = await tski;
    return intRet;
}

我想做的是在发生这种情况时显示进度。但是,只要在进度对话框中包装await行,它就允许原始线程运行并在等待的任务完成之前返回intRet。

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

是否有更好的结构化方法,以便在任务完成之前不会执行返回行。

感谢。

1 个答案:

答案 0 :(得分:1)

不确定为什么你创建了一个线程,这会破坏任务的目的。如果你想在长任务运行时显示一个微调器,只需在显示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;
}