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?
BeginInvoke(DispatcherPriority, Delegate, Object) Executes the specified delegate asynchronously at the specified priority and with the specified argument on the thread the Dispatcher is associated with.
The Dispatcher maintains a prioritized queue of work items for a specific thread. When a Dispatcher is created on a thread, it becomes the only Dispatcher that can be associated with the thread, even if the Dispatcher is shut down.
CurrentDispatcher may create a new instance of Dispatcher depending on the thread from which it was called. That is correct, the Application. Current. Dispatcher is an instance property of the application which is assigned upon construction to be the dispatcher of the current thread.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With