0

I usually exclusively use Application.Current.Dispatcher.BeginInvoke(...) when I need to access the UI thread but is there an appropriate time to use someDependencyObject.Dispatcher.BeginInvoke(...)

I am assuming all the DependencyObjects/UIElements are created on the UI thread so the final result should be the same or similar.

  • What is the difference (if any) between the calls?

  • Is there a rule on when to use one or the other?

nickm
  • 1,775
  • 1
  • 12
  • 14

1 Answers1

3

Not all DispatcherObject instances are necessarily created on the primary UI thread (some applications use a thread per Window approach).

I would personally advise using DispatcherObject.Dispatcher.BeginInvoke as regardless of which thread created the entity, the use of the DispatcherObject in the delegate will succeed.

// Will always work
myTextBox.Dispatcher.BeginInvoke(new Action(myTextBox.Focus));

With Application.Current.Dispatcher.BeginInvoke, the use of the DispatcherObject may fail if the instance was created on a different thread.

// May fail if myTextBox was created on a different thread
Application.Current.Dispatcher.BeginInvoke(new Action(myTextBox.Focus));
Lukazoid
  • 19,016
  • 3
  • 62
  • 85
  • But @Lukazoid: We cant have the control references in the ViewModel rite? and from there if I need to do something in the UI Thread. then What to do? – Arijit May 14 '14 at 07:49
  • @Arijit That sounds like another question, such as this one: [How to pass the UI Dispatcher to the ViewModel](http://stackoverflow.com/questions/2354438/how-to-pass-the-ui-dispatcher-to-the-viewmodel), see if that addresses your question, if not search for a question like yours and if none exists, ask a new question. – Lukazoid May 14 '14 at 08:17