-1

我正在尝试在应用程序保存到数据库时显示进度对话框。我想使用 async await 关键字来执行此操作,但我无法显示进度对话框。我是否必须为此添加一些在 ui 线程上运行的语法?在我的按钮 onclick 事件上将进度对话框添加到异步方法的最简单最简洁的方法是什么?

protected override void OnCreate (Bundle bundle)
{
    base.OnCreate (bundle);
    SetContentView (Resource.Layout.Main);

    Button button_submit = FindViewById<Button> (Resource.Id.button_submit);

    button_submit.Click += async (object sender, EventArgs e) =>  {
        using (ProgressDialog progressDialog = ProgressDialog.Show (this, "Please wait...", "Saving Data", true))
        {
            try
            {
                await this.SaveData();
            }
            finally{
                progressDialog.Dismiss();
            }
        }


    };
}

这是 SaveData 方法

private async Task<bool> SaveData(){


    try{
        //Validate ();

        string connectionString = "Foo"

        SqlConnection dbcon;
        using (dbcon = new SqlConnection(connectionString)) {

            await dbcon.OpenAsync();
            using (SqlCommand dbcmd = dbcon.CreateCommand()) {

                //MERGE UPSERT
                string sql = "bar"

                dbcmd.CommandText = sql;
                dbcmd.Parameters.AddWithValue("@id", this.scanId);

                dbcmd.Parameters.AddWithValue ("@lat", this.geo[0]); 
                dbcmd.Parameters.AddWithValue ("@lng", this.geo[1]);
                dbcmd.Parameters.AddWithValue ("@timestamp", this.timestamp);
                      //commented out to test to make sure slow file io isn't the issue
                //byte[] imageBytes = System.IO.File.ReadAllBytes (photoUri.Path);
                //dbcmd.Parameters.AddWithValue ("@photo", imageBytes);

                var result = await dbcmd.ExecuteNonQueryAsync();

                if (result != 1)
                    throw new Exception("Save encountered an error " + result);
            }
        }
        //ResetData ();
        RunOnUiThread(() => Toast.MakeText (this, "Data Saved", ToastLength.Long).Show ());
        return true;
    }
    catch (Exception ex) {
        RunOnUiThread(() => Toast.MakeText (this, ex.Message, ToastLength.Long).Show ());
        return false;
    }



}
4

1 回答 1

-2

试试这个里面的按钮点击..这很简单

ProgressDialog progress = new ProgressDialog(this);
progress.Indeterminate = true;
progress.SetProgressStyle(ProgressDialogStyle.Spinner);
progress.SetMessage("Loading... Please wait...");
progress.SetCancelable(false);

RunOnUiThread(() =>
{
    progress.Show();
});
Task.Run(()=>
//here savedata method
).ContinueWith(Result=>RunOnUiThread(()=>progress.Hide()));
于 2017-05-02T13:35:45.813 回答