2013-10-14 41 views
-1

我試圖在應用程序保存到數據庫時進行進度對話框顯示。我想使用async await關鍵字來完成它,但我無法顯示進度對話框。我是否必須在ui線程語法上添加一些運行?在我的按鈕onclick事件中,將進度對話框添加到異步方法最簡單最簡單的方法是什麼?無法獲取progressdialog以顯示異步等待方法

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


    }; 
} 

這裏是保存數據的方法

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

請問你的原代碼的行爲,如果你更換'等待this.SaveData( )'with'等待Task.Run(()=> SaveData())'? –

+0

,讓進度顯示正確,但在Dismiss()方法我得到的錯誤「不能創建處理程序內部線程沒有調用Looper.prepare()」 – MonkeyBonkey

+0

由於Task.Run'確實讓進展顯示,這表明'SaveData'實際上並不是異步的(就像@Servy評論過的那樣)。你的問題在'SaveData'中。 –

回答

-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()));