C# WPF TextBlock Text shows only after stored procedure execution completed

时间:2017-08-04 12:43:04

标签: c# wpf

I have simple app, which execute stored procedure from SQL Server 2008 R2. Here is code:

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

Then I'm calling this method on ButtonClick like this:

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

Why text from (TextBlock named InfoText) InfoText.AppendText("START"); shows after stored procedure execution is done ? Is it because threads etc. ? Any ideas ? Thanks.

1 个答案:

答案 0 :(得分:4)

Because this is the UI thread that you're using to run the stored procedure, which is the same thread responsible to update the UI. So, it is busy running the stored procedure instead of updating the UI.

You should always try to make the UI thread run as fast as possible so that your UI won't get stuck. So, in your case, you should be doing:

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