Case

Can progress event of BackgroundWorker execute after completed event?At first you might think no, but when you try this with Console application, you'll be able to reproduce this issue. Now question is: how come this scenario occurs in Console app and not in Windows Forms? Seems petty interesting, 

Windows Forms scenario

Now coming to Windows forms, this issue will never occur, due to message queuing support. Windows message queue takes very good care of execution sequence of the events. This clearly mean 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 talking about Console application, none of the above holds true. There is no SynchronizationContext installed and the events just end up in getting run in threadpool thread, which doesn't guarantee any order. 

Test case

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

Console.WriteLine("One");

Console.WriteLine("Two");

Console.WriteLine("Three");

Console.WriteLine("Four");

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

Source

Another source : http://www.codeproject.com/Tips/387783/BackgroundWorker-in-NET-Console-Application

Published by same author , on 21 May 2012