AFAIK, this event is promised to be called in the creator thread (BackgroundWorker RunWorkerCompleted Event); and in the most cases, it does as promised. However, sometimes RunWorkerCompleted is called not in the thread that created BackgroundWorker object.
Update: Code is like this:
Trace.WriteLine(Thread.CurrentThread.ManagedThreadId);
var worker = new BackgroundWorker();
worker.DoWork += (s, args) => Trace.WriteLine(Thread.CurrentThread.ManagedThreadId);
worker.RunWorkerCompleted += (s, args) => Trace.WriteLine(Thread.CurrentThread.ManagedThreadId);
worker.RunWorkerAsync();
Output is 1 7 7 (correct output must be 1 7 1)
Any ideas?
BackgroundWorker is designed for GUI applications.
I’m guessing you’re doing this in a console application or some other type of application other than Winforms or WPF.
BackgroundWorker uses the synchronization model provided by SynchronizationContext.Current to dispatch events. In a GUI application, SynchronizationContext.Current is initialized with a
WindowsFormsSynchronizationContext, which provides synchronization by Invoking on the UI thread.But in a non-GUI application, SyncronizationContext.Current is just a
SynchronizationContextobject, which (from MSDN):In other words it simply dispatches via the threadpool, so you’ll usually get a different thread each time.
If you run your code in a winforms application, it will work as expected.