BackgroundWorker does not fire the RunWorkerCompleted event

I am creating a backgroundworker not in my Windows form, but in a class file (BusinessLogic) that implements all the processing. From the main form, I first call the BL method, which initializes BGW. Then I call the BL method, which will start BGW.

Here is more background :) on my implementation. How to use BackGroundWorker in a class file?

The DoWork event runs normally, but it does not call RunWorkerCompleted.

Some search engines and I found out this link. I feel like my problem is the same as these guys. http://www.eggheadcafe.com/software/aspnet/29191764/backgroundworker-does-not-fire-the-runworkercompleted-event.aspx

I would be grateful for any material on this issue. Thanks in advance.

The code in the 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; } 
+6
source share
2 answers

The completed event is called into the main thread. It must be raised and executed by MessagePump.

However, your wait and wait code blocks the message loop.

  Hide(); .... while (!BusinessLogic.firstCycleDone) { Thread.Sleep(100); } Show(); 

The answer here is that you are not using a background worker or other form of streaming ...

Just call bgWorker_DoWork() directly:

  // Hide(); bgWorker_DoWork(); // rename Show(); 
+6
source

if you just call Application.DoEvents(); instead of Sleep(100); your code will work, but, as I said earlier, the BackgroundWorker class is a bug, and I would personally use my own threads and reports

Alternatively, you can sleep a bit and then call DoEvents

-1
source

Source: https://habr.com/ru/post/892660/


All Articles