Progress bar for long running task in C#

2019-05-10 20:20发布

问题:

My application runs some database queries that can take a long time.

While executing these queries, my application appears to freeze and it looks like the application has stopeed working.

I need to use progressbar to avoid this problem but I am not sure how can predict the time that the query will take to execute.

The code runing the query is below

private void CheckSsMissingDate()
 {
  while (DateTime.Parse(time) <= DateTime.Now)
   {
     var ssCon = OpenSQLConnection();
     var cmd = new SqlCommand("SELECT TOP (1)Date_Time,Value1,Value2,Value3,Value4,Value5,Value6,
         "+ "Value7,Value8,Value9 from RAW_S001T01 where Date_Time >='" + tempTime + "'",ssCon);
     var dr = cmd.ExecuteReader();
     var count = 0;
     while (dr.Read())
      {
        ssChkDate = (dr["Date_Time"].ToString());
        conssChkDate = DateTime.Parse(ssChkDate).ToString("yyyy-MM-dd HH:mm:ss");
        tempTime = Convert.ToDateTime(ssChkDate);
        tempTime = tempTime.AddMinutes(15);
        TValue1 = (dr["Value1"].ToString());
        TValue2 = (dr["Value2"].ToString());
        TValue3 = (dr["Value3"].ToString());
        TValue4 = (dr["Value4"].ToString());
        TValue5 = (dr["Value5"].ToString());
        TValue6 = (dr["Value6"].ToString());
        TValue7 = (dr["Value7"].ToString());
        TValue8 = (dr["Value8"].ToString());
        TValue9 = (dr["Value9"].ToString());
        if (CheckMsMissingDate(conssChkDate) == false)
          {
            InsertMissing(conssChkDate,TValue1,TValue2,TValue3,TValue4,TValue5,TValue6,TValue7,TValue8,TValue9);
                    count = count + 1;
           }
        }
       dr.Close();
       ssCon.Close();
       updateCount.Text = count + @" Missing Records added.";
    }
}

How can I show a progress bar to show the progress of the query?

回答1:

You may use BackgroundWorker() to solve this kind of problems.

First of all define a global variable of class BackgroundWorker() like

private BackgroundWorker bgw;

then use below code in starting of your query execution like button1_Click() event or anything.

bgw = new BackgroundWorker();
bgw.WorkerReportsProgress = true;
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.RunWorkerAsync();

Now define the methods as below:

void bgw_DoWork(object sender, DoWorkEventArgs e)
 {
  //Your time taking work. Here it's your data query method.
  CheckSsMissingDate();
 }

void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
 {
   //Progress bar.
   progressBar1.Value = e.ProgressPercentage;
 }

 void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  {
   //After completing the job.
   MessageBox.Show(@"Finished");
  }


回答2:

If you don't want your application to freeze,you should use the async/await keywords recently implemented in C#,or you could write your async code manually.

Reference : MSDN