Reputation: 45
I have created a textbox on my form to let the user know the status of the procedure they have initiated. The first value to be displayed in this tb is "Calculating report...". This field is updated 3 times total during the process, but only the final value is ultimately visible.
private void bRun_Click(object sender, EventArgs e)
{
tRunTime.Text = "Calculating report...";
SqlConnection conn = new SqlConnection(connection);
conn.Open();
this.Cursor = Cursors.WaitCursor;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
using (conn)
{
try
{
//my code...
}
catch (Exception r)
{
MessageBox.Show("Error: " + r, "Report Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
tRunTime.Text = "Calculation complete. Exporting to Excel...";
string sqlReport = "my sql string";
//Populate dataset
SqlDataAdapter adapterReport = new SqlDataAdapter(sqlReport, conn);
DataSet dsReport = new DataSet();
dsReport.Tables.Add(sqlReport);
adapterReport.Fill(dsReport, sqlReport);
ExportDataSetToExcel(sqlReport); // Local custom process that I use on many forms. It works perfectly.
Process.Start(@"path to temp file");
}
conn.Close();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
tRunTime.Text = "Report run time: " + elapsedTime;
this.Cursor = Cursors.Default;
}
Everything here works perfectly, except the first two status stages ("Calculating report..." and "Calculation complete. Exporting to Excel...") never actually appear on the form.
I am somewhat new to C#, so if you see other improvements to me code, I am all ears as well.
Thanks in advance!
Upvotes: 0
Views: 64
Reputation: 457
The UI is single threaded therefore causing it not to respond completely during a long running task.
Try using a BackgroundWorker
or another Thread
with delegates. Both should allow for multi threading with access to the UI.
Upvotes: 1