Consider the following code:
private static BackgroundWorker bg = new BackgroundWorker();
static void Main(string[] args) {
bg.DoWork += bg_DoWork;
bg.P
Do not use this solution!!! May lead to deadlocks as SLaks has pointed it out.
I seem to have stumbled upon an answer. I changed the code the following way:
[MethodImpl(MethodImplOptions.Synchronized)]
static void bg_ProgressChanged(object sender, ProgressChangedEventArgs e) {
Console.WriteLine(e.ProgressPercentage);
Thread.Sleep(100);
Console.WriteLine(e.ProgressPercentage);
}
and now I get the output I want:
0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
BackgroundWorker
raises ProgressChanged
events on the current SynchronizationContext of the thread that called RunWorkerAsync()
.
The default SynchronizationContext runs callbacks on the ThreadPool without any synchronization.
If you use BackgroundWorker in a UI application (WPF or WinForms), it will use that UI platform's SynchronizationContext, which will execute callbacks in order.