我正在尝试在应用程序保存到数据库时显示进度对话框。我想使用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;
}
}
答案 0 :(得分:-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()));