BackgroundWorker in .NET Console Application

Today, I was casually surfing the net, and came across one interesting question 'can the progress event of the BackgroundWorker execute after a completed event?'. At first I thought no, but when I tried this with the Console application, I was also able to reproduce this issue. Now the question is, how come this scenario occurs in a Console app and not in the Windows Forms. Pretty interesting, right?

Windows Form Scenario

Now, coming to the Windows form, this issue will never occur, due to the message queuing support. Windows message queue takes a very good care of the execution sequence of the events. This clearly means that the progress event may run after the DoWork has completed, but the completion event will always happen afterwards. Another interesting thing here, is the SynchronizationContext, which helps in maintaining all these sequencing.

Console App Scenario

But when we are talking about the Console application, none of the above holds true. There is no SynchronizationContext installed and the events just end up in getting run in the threadpool thread, which doesn't guarantee any order.

Test case

I created a console app and used the Backgroundworker with all the required event handlers. In the progress event handler, I added the below lines:

Console.WriteLine("One");

Console.WriteLine("Two");

Console.WriteLine("Three");

Console.WriteLine("Four");

On executing the console application, I found out that the output messages are not in the order that I mentioned in the code. When seeking the standard output, I sometimes received Two, Three, Four, One, again, sometimes I received One, Two, Three, Four and sometimes, I also found one of the message missing and in the output I got only Two, Three and Four. But in the Windows Form, I always get the output in the correct order as One, Two, Three, Four.

I hope the above analogy makes sense.

Next Recommended Reading Use Log4Net in C# Console Application