I have a simple threaded program that is simply counting up. This process should take up all processor resources because it is such a long loop. I programmed it using a BackgroundWorker thread. So there should be two flows. The main program, and the background counter. However when the program runs, the application locks and the screen does not update. I tested it, and the UpdateStatus is being called with the incremented values. Why is the BackgroundWorker preventing events in the main program thread from executing?
I realize that I can include a Application.DoEvents(); but that would defeat the purpose of using a thread in the first place (allow multiple processes equal share). Why is the BackgroundWorker causing to main program thread to stop responding?
int numTest1 = 0;
public Form1()
{
InitializeComponent();
_worker = new BackgroundWorker();
_worker.WorkerReportsProgress = true;
_worker.DoWork += TestCounter;
_worker.ProgressChanged += UpdateStatus;
_worker.RunWorkerCompleted += FinalUpdate;
}
private void btnStart_Click(object sender, EventArgs e)
{
_worker.RunWorkerAsync();
}
private void TestCounter(object sender, DoWorkEventArgs e)
{
for (int loopCount = 0; loopCount < 1000000000; loopCount++)
{
numTest1 += 1;
_worker.ReportProgress(0);
}
}
private void UpdateStatus(object sender, ProgressChangedEventArgs e)
{
lblTestUpdate.Text = numTest1.ToString();
}
private void FinalUpdate(object sender, RunWorkerCompletedEventArgs e)
{
lblTestUpdate.Text = numTest1.ToString();
lblTestResult.Text = "Done";
}