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?
You may use
BackgroundWorker()
to solve this kind of problems.First of all define a global variable of class
BackgroundWorker()
likethen use below code in starting of your query execution like
button1_Click()
event or anything.Now define the methods as below:
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