0

I would like to know, what is the best/safest way to access the main UI thread from another thread.

Should i use Dispatcher.BeginInvoke?

_cancelationTokenSource = new CancellationTokenSource();
        new Task(() =>
            {
                Dispatcher.BeginInvoke((Action)(() =>
                {
                    //process data
                }));
            }, _cancelationTokenSource.Token, TaskCreationOptions.LongRunning).Start();

or should i use Dispatcher.Invoke?

    _cancelationTokenSource = new CancellationTokenSource();
        new Task(() =>
            {
                Dispatcher.Invoke((Action)(() =>
                {
                    //process data
                }));
            }, _cancelationTokenSource.Token, TaskCreationOptions.LongRunning).Start();

What is the main difference between the 2 Invoke methods?

What will the performance impact be when using BeginInvoke and Invoke?

Most important, i would like to keep my UI responsive.

Willem
  • 9,166
  • 17
  • 68
  • 92
  • http://stackoverflow.com/questions/229554/whats-the-difference-between-invoke-and-begininvoke check this one – 62071072SP Sep 20 '11 at 09:03
  • I guess you're reffering to the WPF, since it's quite different than winforms... – Amittai Shapira Sep 20 '11 at 09:04
  • Do I get this right: You create a task for asynchronous execution, but in this task delegate the heavy calculation again to the UI thread. I'm wondering what you need a task for? Wouldn't you need to process data in the task and invoke the dispatcher only to update the UI? Otherwise you block the UI thread by whatever you do in `//process data` – Andreas Sep 20 '11 at 09:16

1 Answers1

1

Invoke() if you want to call it synchronous and BeginInvoke() for async .. if you use BeginInvoke you will need to pass the delegate to be called when the operation is finished.

You are already on a background thread so UI will remain responsive either way. Just depends on whether you want this thread's execution to wait for the operation to finish or if you want it done in the background while this thread's execution continues.

iDevForFun
  • 978
  • 6
  • 10