private void button1_Click(object sender, EventArgs e)
{
backworker.RunWorkerAsync();
}
private void backworker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 10000; i )
{
label1.Text = i.ToString();
DateTime d2 = DateTime.Now;
label2.Text = d2.ToString();
}
}
Friends i am working on comparing times between when the task of backworker finished, like how much time it tooks to finish the loop task
but when i do it, i tried to put the Comparasion after loop but it tells me error because d2 not declared
so how can i solve that to compare and get the exact time that the loop took to finish the task of printing numbers
CodePudding user response:
I think this could work:
DateTime d2 = DateTime.Now;
for (int i = 0; i < 10000; i )
{
...
}
label2.Text = (DateTime.Now - d2).ToString();
A good way to measure times is to use System.Diagnostics.Stopwatch
:
var sw = Stopwatch.StartNew();
for (int i = 0; i < 10000; i )
{
...
}
label2.Text = sw.Elapsed.ToString();
CodePudding user response:
Your DateTime
is declared withing the loop and therefore its scope is limited to the loop body. You must declare it before, i.e., outside, the loop to make it available after the loop. But it is better to use a Stopwatch for this purpose.
Another problem is that you are attempting to access a Control (a Label) from another thread than the UI thread. You are not allowed to do this.
Fortunately the BackgroundWorker Class can "Talk" to the UI thread through the ProgressChanged
event.
Setup the BackgroundWorker with:
private void button1_Click(object sender, EventArgs e)
{
backworker.WorkerReportsProgress = true;
backworker.RunWorkerAsync();
}
Then declare another event handler which will automatically be called in the UI-thread:
private void Backworker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
label1.Text = e.ProgressPercentage.ToString();
var ts = (TimeSpan)e.UserState;
label2.Text = ts.ToString(@"ss\.ff");
}
Now, change you worker to
private void Backworker_DoWork(object sender, DoWorkEventArgs e)
{
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 100; i ) {
Thread.Sleep(100);
backworker.ReportProgress(i, stopWatch.Elapsed);
}
stopWatch.Stop();
backworker.ReportProgress(100, stopWatch.Elapsed);
}
Note that I have introduced a Thread.Sleep(100);
and have diminished the number of loops by 100. This is because otherwise the UI cannot display the progress that fast. In a real scenario you would replace Thread.Sleep
by some useful work.