Friday, May 18, 2012

BackgroundWorker in .Net Console Application


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


Now coming to Windows form, 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.


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: I created a console app and used Backgroundworker with all the required event handlers. In progress event handler, I added 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 Form, I always get the output in correct order as One, Two, Three, Four.


I hope, above analogy makes sense.

No comments:

Post a Comment