Home > Net >  BackgroundWorker isn't working if I don't use Thread.Sleep on WinForms
BackgroundWorker isn't working if I don't use Thread.Sleep on WinForms

Time:10-04

Here is my simple code:

private void button1_Click(object sender, EventArgs e)
{
    if (backgroundWorker1.IsBusy) return;
    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    var worker = sender as BackgroundWorker;

    for (var i = 1; i <= 10000; i  )
    {
        Thread.Sleep(1);
        worker?.ReportProgress(i);
    }
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    label1.Text = e.ProgressPercentage.ToString();
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    label1.Text = "Completed.";
}

This code works correctly. But If I remove Thread.Sleep(1); from the code, BackgroundWorker does not work. I couldn't find where the error came from in such a simple thing.

CodePudding user response:

There's no need to report the progress so often.

Do something like this:

for (var i = 1; i <= 10000; i  )
{
    Thread.Sleep(1);
    if (i % 100 == 0)
    {
        worker?.ReportProgress(i);
    }
}

Or you could check the time or tickcount, and when you've seen 50ms of time has elapsed then do a ReportProgress. There's no point doing it more often than that.

Also, you could batch the updates to your GridView to make it more efficient/less wasteful - sending so many rows 1 row at a time is going to have more overhead doing it one at a time.

  • Related