Using C# .NET 3.5.
It seems I'm not the only one, since a search seems to bring up a lot of similar questions, however reading through them I seem still to be missing the solution.
I'm raising an event with a button click on my UI, which is then supposed to start a backgroundWorker to get some time consuming work done - in this case, I want it to collect information from a form and a) write to an xml file as well as b) insert the information into a remote database.
This is exactly what the backgroundWorker was designed and intended to do I believe.
Here is the event raising code.
private void btnFinish_Click(object sender, EventArgs e)
{
clkFinish.setInstant();
curAct.setTimeFinish(DateTime.Now);
btnStart.Enabled = true;
bgwDataWorker.RunWorkerAsync();
for (int i = 0; i < 20; i++)
{
Console.WriteLine("Thread a: " + i);
Thread.Sleep(100);
if (i == (20 - 1))
{
Console.WriteLine("Finished");
}
}
}
As you can see, I have some code there which I've used as a counterbalance to the background worker code, which is here:
private void bgwDataWorker_DoWork(object sender, DoWorkEventArgs e)
{
Console.WriteLine("Running in a different thread now");
int count = 0;
for (int i = 0; i < 21; i++)
{
Console.WriteLine("Thread b: " + i);
Thread.Sleep(100);
(sender as BackgroundWorker).ReportProgress(5 * i, null);
if (i == (21 - 1))
{
count = i;
}
}
e.Result = count;
}
So far, everything seems to be working up to this point.
My problem is that when the code in the DoWork method is finished, nothing is happening. Here are the ProgressChanged and RunWorkerComplete methods.
private void bgwDataWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine(e.ProgressPercentage);
}
private void bgwDataWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine("Result is " + e.Result.ToString());
}
This has me baffled.
I've tried running the examples from MSDN and I'm experiencing the same problems. RunWorkerCompleted and ReportProgress events are simply not being raised for some reason and I don't understand why.
Thanks for reading.
Alan
I had the same problem and I just figured out the answer.
In the properties of the backgroundworker, make sure that ProgressChanged and RunWorkerCompleted list the name of their functions (mine are called 'backgroundWorker1_ProgressChanged' and 'backgroundWorker1_RunWorkerCompleted' respectively).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With