Reputation: 437
I'm creating backgroundworker not in my windows form but in the class file (BusinessLogic) that implements all the processing. From main form I first call the BL method that initializes the BGW. Then I call the method of BL which will start the BGW.
Here is more background :) on my implementation. How to use BackGroundWorker in class file?
The DoWork event runs fine but it doesnt call the RunWorkerCompleted.
Some googling and I found out this link. I've a feeling that my problem is same as this guys. http://www.eggheadcafe.com/software/aspnet/29191764/backgroundworker-does-not-fire-the-runworkercompleted-event.aspx
I'd appreciate any input on this issue. Thanks in advance.
Code in Main form:
private void frmMain_Load(object sender, EventArgs e)
{
Hide();
BusinessLogic.BGWInitialize();
BusinessLogic.StartBackgroundWorker();
while (!BusinessLogic.firstCycleDone)
{
Thread.Sleep(100);
}
Show();
}
Code in BusinessLogic:
public static void BGWInitialize()
{
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgressChanged);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
bgWorker.WorkerReportsProgress = true;
}
public static void StartBackgroundWorker()
{
bgWorker.RunWorkerAsync();
}
private static void bgWorker_RunWorkerCompleted(
object sender, RunWorkerCompletedEventArgs e)
{
firstCycleDone = true;
}
Upvotes: 8
Views: 12777
Reputation: 1145
if you would just call Application.DoEvents();
instead of Sleep(100);
your code would work, but as I said previously BackgroundWorker
class is a buggy thing and I would personally use my own threads and reports
Alternatively you could sleep a bit and then call DoEvents
Upvotes: 0
Reputation: 273244
The completed event is Invoked to the main thread. It is supposed to be picked up and executed by the MessagePump.
However, your Wait-and-Sleep code is blocking the message loop.
Hide();
....
while (!BusinessLogic.firstCycleDone)
{
Thread.Sleep(100);
}
Show();
The answer here is that you have no use for a Backgroundworker or another form of threading...
Just call bgWorker_DoWork()
directly:
// Hide();
bgWorker_DoWork(); // rename
Show();
Upvotes: 7