2017-08-04 44 views
0

我有一個簡單的應用程序,它可以從SQL Server 2008 R2執行存儲過程。這裏是代碼:C#WPF TextBlock僅在存儲過程執行完成後才顯示文本

private void CloseDay() 
    { 
     ConnectToDatabase(); 

     string query = "SELECT [DateTime],EmployeeId,EventTypeId" + 
         " FROM [Events] WHERE cast([DateTime] as date) between " + 
         "cast(@od as date) and cast(@do as date)"; 
     SqlCommand sql = new SqlCommand(query, conn); 
     sql.Parameters.AddWithValue("od", DataOd.Text); 
     sql.Parameters.AddWithValue("do", DataDo.Text); 
     SqlDataAdapter sda = new SqlDataAdapter(sql); 
     DataTable dt = new DataTable(); 
     sda.Fill(dt); 

     foreach (DataRow row in dt.Rows) 
     { 
      SqlCommand procedure = new SqlCommand("up_rozlicz_dzien", conn); 
      procedure.CommandType = CommandType.StoredProcedure; 
      procedure.Parameters.AddWithValue("@kodp", Convert.ToInt32(row[1])); 
      procedure.Parameters.AddWithValue("@data", DataOd.Text); 
      procedure.Parameters.AddWithValue("@calId", 23); 
      procedure.ExecuteNonQuery(); 
     } 
    } 

然後我打電話這樣的ButtonClick這種方法:

private void EndButton_Click(object sender, RoutedEventArgs e) 
    { 
     InfoText.AppendText("START"); 

     var watch = new Stopwatch(); 
     watch.Start(); 
     CloseDay(); 
     watch.Stop(); 
     var diff = watch.ElapsedMilliseconds/1000; 
     InfoText.AppendText("\nEXECUTION TIME: " + diff.ToString()); 
    } 

爲什麼從文本(TextBlock的命名信息文本)InfoText.AppendText("START");節目後存儲過程的執行做了什麼?是因爲線程等嗎?有任何想法嗎 ?謝謝。

+0

什麼是'InfoText'? – Michael

+0

@Michael TextBlock被命名爲InfoText,抱歉。 – fanarek

+2

您正在同一個線程上執行您的代碼。它只會在成功後纔會顯示。你將不得不在另一個線程上調用'CloseDay'。 – XAMlMAX

回答

4

因爲這是您用來運行存儲過程的UI線程,這是與更新UI相同的線程。所以,它正忙於運行存儲過程而不是更新UI。

您應該始終儘可能快地運行UI線程,以便您的UI不會卡住。所以,你應該這樣做:

private void EndButton_Click(object sender, RoutedEventArgs e) 
{ 
    InfoText.AppendText("START"); 

    Task.Run(
    () => 
    { 
     var watch = new Stopwatch(); 
     watch.Start(); 
     CloseDay(); 
     watch.Stop(); 

     var diff = watch.ElapsedMilliseconds/1000; 

     InfoText.Dispatcher.Invoke(() => InfoText.AppendText("\nEXECUTION TIME: " + diff.ToString())); 
    }); 
} 
相關問題