Introduction
Behavior of BackgroundWorker
thread for Console and Windows Forms apps.
Background
Today I was just doing net surf and came across an interesting question: 'Can the progress event of
BackgroundWorker
execute after completed event'. At first I thought no, but when I tried this with a 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 Windows Forms. Pretty interesting, right? Now coming to Windows Forms, this issue will never occur
due to message queuing support. The 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 a 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.
Using the code
I created a console app and used 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");
Points of Interest
On executing the console application, I found that output messages are not in order, which I mentioned in code. On the standard output, I received
Two, Three, Four, One and sometimes I received One, Two, Three, Four and sometimes, I also found one of the messages missing and in the output, I got only Two,
Three, Four. But in Windows Forms, I always get the output in the correct order as One, Two, Three, Four.