4

I know the technique about UI thread updating from another thread.

So I have these two methods/techniques, which one should I use?

Using Task:

var uiTask = Task.Factory.StartNew(() => {
  // change something on ui thread
  var action = theActionOnUiThread;
  if (action != null) {
    action();
  }
}, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());

Using Dispatcher:

Dispatcher.CurrentDispatcher.BeginInvoke(
  new Action(() => {
    // change something on ui thread
    var action = theActionOnUiThread;
    if (action != null) {
      action();
    }
  }));
punker76
  • 14,326
  • 5
  • 58
  • 96

2 Answers2

2

From a technical point of view I doubt there is a 'best' here. however I'd go with the dispatcher approach:

  • it makes your intent more clear, namely that you want to get something done on the main ui thread
  • you don't need to boter with all the task factory options
  • Dispatcher makes it easier to hide everything behind an interface (1) allowing easy dependency injection and unit testing

(1) see here for example

stijn
  • 34,664
  • 13
  • 111
  • 163
1

TaskScheduler.FromCurrentSynchronizationContext() does not guarantee returning you a TaskScheduler for the UI thread.

In fact it can sometimes return null, although these cases are rare and generally involve spinning up your own dispatcher in a native app (for example the WIX bootstrapper).

So I'd say it's safer to use the dispatcher version.

Cameron MacFarland
  • 70,676
  • 20
  • 104
  • 133