I wrote a simple app that adds 100000 lines of "Hello World" to a list using a BackgroundWorker.
Below is the code of the work that my backgroundworker is doing in a separate thread:
private void BgWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
int min = 0;
foreach (var hw in hwList)
{
//new ManualResetEvent(false).WaitOne(1);
Thread.Sleep(1);
int progress = Convert.ToInt32((Double)min / hwList.Count * 100);
min++;
bgWorker.ReportProgress(progress);
}
}
// Updating the progress
private void BgWorkerOnProgressChanged(object sender, ProgressChangedEventArgs progressChangedEventArgs)
{
ProgressBar.Value = progressChangedEventArgs.ProgressPercentage;
}
All is working fine, except that if I remove the Thread.Sleep(1) the BackgroundWorker doesn't report the progress anymore. (I suppose it needs some time). Suspending the thread for 1 ms actually makes the BackgroundWorker report the progress but it's very slow.
My question is, is there a way I can get rid of thread sleeping but at the same time making the BackgroundWorker report the progress correctly?
From my understanding, suspending the BackgroundWorker is inevitable, since the thread needs some time to perform the task, but I'm wondering if there's a workaround.
I had issues where i was reporting progress to often, furthermore there is no reason to report the same progress so many times waste of cpu cycles.