Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF/threading: Dispatcher static vs Dispatcher on a control?

Tags:

c#

wpf

I'm a bit confused in terms of the dispatcher. Say I'm on a background thread doing some kind of long operation. I'd like to update the ui thread I understand I do this through the dispatcher. My question is, do i call the dispatcher statically like: Dispatcher.BeginInvoke(mywork) ... Or on the control i want to update: mytextbox.Dispatcher.BeginInvoke(mywork)

like image 926
Shai UI Avatar asked Jan 06 '11 22:01

Shai UI


1 Answers

It's worth noting that calling Dispatcher.BeginInvoke isn't a static call: it's an implicit this.Dispatcher.BeginInvoke. If you can use this call, you're likely writing your code from within a control or window already. In that case, you're probably safe to call either since most of the time there will be one UI thread per application.

The actual static call would be Dispatcher.CurrentDispatcher.BeginInvoke, which is not something you want to call (see my comment on Hasan Khan's answer for why).

EDIT: Calling Application.Current.Dispatcher is not a bad thing. (And, for clarity, it's an instance property, not a static - being called on a static/singleton instance of Application.) This property will return the Dispatcher for the thread that the app was created with, and typically that's the thread that the UI is created on aswell - so Application.Current.Dispatcher returns the same Dispatcher as myWindow.Dispatcher would.

The static call Dispatcher.CurrentDispatcher (that I warned against) returns a Dispatcher for the thread you call it from. If you call it from a background thread, you'll get a new Dispatcher created especially for that thread - which often isn't what's wanted.

like image 100
Dan Puzey Avatar answered Sep 18 '22 06:09

Dan Puzey