在C#中长时间运行的任务进度条 [英] Progress bar for long running task in C#
问题描述
我的应用程序运行时,可以采取很长一段时间了一些数据库查询。
My application runs some database queries that can take a long time.
在执行这些质疑,我的应用程序似乎冻结,它看起来像应用程序已经stopeed工作
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.
乳宁查询的代码如下
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?
推荐答案
您可以使用的BackgroundWorker()
来解决这样那样的问题。
You may use BackgroundWorker()
to solve this kind of problems.
首先定义类的全局变量的BackgroundWorker()
类似
First of all define a global variable of class BackgroundWorker()
like
private BackgroundWorker bgw;
然后用下面的代码在你的查询执行的开始像的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");
}
这篇关于在C#中长时间运行的任务进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!