19

I have seen this Deployment.Current.Dispatcher.BeginInvoke( ()=> {...} ) format in some code .Is it used to do some work in Background?What are the general uses of it?

Vaysage
  • 1,326
  • 2
  • 15
  • 30

3 Answers3

41

No, it's not to do work in a background thread - it's to do work on the UI thread. So it's normally called from a background thread, in order to manipulate the UI, which can only be done on the UI thread.

The body of the lambda expression is the code which you want to execute in the UI thread.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Jon, the popularity of your posts on SO is exceptional. My hat is off to you :) – Mick N Jan 13 '11 at 11:12
  • 8
    It's also important to mention that BeginInvoke can be used from the UI thread itself to a followup action on the UI thread after the existing UI action queue is empty. Essentially postponing work until the UI thread is no longer doing anything. – JustinAngel Jan 14 '11 at 23:13
  • @JonSkeet: how can i execute a code in a background thread, as this code is blocking my progress bar from showing on UI – RobertKing Jul 21 '14 at 11:22
  • @Rohaan: Well it depends on what the code needs to do. If it's building the UI, it *shouldn't* be on a background thread. If it's fetching data from elsewhere (for example) then it's appropriate to do in a background thread. It's not clear that that's clearly related to this question though... – Jon Skeet Jul 21 '14 at 11:25
  • @JonSkeet: Thanks for the reply...http://stackoverflow.com/questions/24858710/how-to-perform-operation-on-a-background-thread please see the question i posted today on above link – RobertKing Jul 21 '14 at 11:30
6

When code that updates the UI executes from a thread other than the UI thread, an invalid cross-thread access exception occurs.

The dispatcher allows you to pass some code over to the UI thread from another thread.

The project I put in this post demonstrates this, among other concepts.

WebClient, HttpWebRequest and the UI Thread on Windows Phone 7

the_drow
  • 18,571
  • 25
  • 126
  • 193
Mick N
  • 14,892
  • 2
  • 35
  • 41
2

you'll need to use Deployment.Current.Dispatcher in a SilverLight application when you find yourself doing work in a non UI worker thread (within a context that does not inherit from DependencyObject) and you need to update the UI.

ehosca
  • 945
  • 7
  • 16