0

According documentation I can access UI from BackgroundWorker.RunWorkerCompleted event. But according my experiment in console application main thread and RunWorkerCompleted thread are different (since thread ID's are different). And this is not acceptable for UI update. How to explain this situation?

static BackgroundWorker _bw = new BackgroundWorker();

        static void Main(string[] args)
        {
            _bw.DoWork += DoWork;
            _bw.WorkerReportsProgress = true;
            _bw.RunWorkerAsync("hello");
            _bw.RunWorkerCompleted += _bw_RunWorkerCompleted;
            _bw.ProgressChanged += _bw_ProgressChanged;
            Console.WriteLine("done "+ Thread.CurrentThread.ManagedThreadId);

            Console.ReadLine();
        }



        private static void _bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Console.WriteLine("RunWorkerCompleated " + Thread.CurrentThread.ManagedThreadId);
        }

        private static void DoWork(object sender, DoWorkEventArgs e)
        {
            Console.WriteLine(e.Argument+ " "+Thread.CurrentThread.ManagedThreadId );
        }

Output:

done 1
hello 3
RunWorkerCompleated 5
vico
  • 17,051
  • 45
  • 159
  • 315

2 Answers2

2

Your code doesn't have a UI thread. Since you don't have a UI thread, and didn't call RunWorkerAsync from a UI thread (which is required for it to know what UI thread to marshall the event handlers to) it can't call any of the event handlers in a (non-existent) UI thread.

Create a UI application (a winforms or WPF application, for example), make sure to create and run the BGW from a UI thread, and then you'll see that you can manipulate the controls from the various events (other than DoWork, obviously).

Servy
  • 202,030
  • 26
  • 332
  • 449
0

Yes you can access UI from BackgroundWorker.RunWorkerCompleted given that you have an UI thread.

The reason why console application runs the event in a separate thread is because console application doesn't have a SynchronizationContext.It is something that's responsible to manage thread switching for async operations.

Steve
  • 11,696
  • 7
  • 43
  • 81