我的应用程序运行一些数据库查询,这可能需要很长时间。
在执行这些查询时,我的应用程序似乎死机了,看起来该应用程序已停止工作。
我需要使用progressbar来避免此问题,但是我不确定如何预测查询执行所花费的时间。
运行查询的代码如下
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."; } }
如何显示进度条以显示查询的进度?
您可以BackgroundWorker()用来解决这类问题。
BackgroundWorker()
首先定义一个类的全局变量,BackgroundWorker() 例如
private BackgroundWorker bgw;
然后在执行查询(如button1_Click()事件或其他任何内容)的过程中使用下面的代码。
button1_Click()
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();
现在定义如下方法:
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"); }