Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple example of DispatcherHelper

I'm trying to figure out how can I use DispatcherHelperftom MVVM light toolkit in SL, but I can't find any example.

From home page of this framework I know that

DispatcherHelper class, a lightweight class helping you to create multithreaded applications.

But I don't know how to use it.

How and for what I can use it?

like image 902
user278618 Avatar asked Sep 13 '11 12:09

user278618


1 Answers

You only need the DispatcherHelper when yo want to make changes to components on your UI thread, from code that runs on a different thread. E.g. in an Silverlight application you call a web service to retrieve some data asynchroneously, and now want to inform the Ui that the data is present via a OnNotifyPropertyChanged event.

First you have to initialize the DispatcherHelper. In Silverlight you do this in Application_Startup:

//initialize Dispatch helper
private void Application_Startup( object sender, StartupEventArgs e) {
    RootVisual = new MainPage();
    DispatcherHelper.Initialize(); 
}

In WPF the initialization is done in the static constructor of you App class:

static App() { 
    DispatcherHelper.Initialize();
}

Then in your event, handling the completion of your asnc call, use the following code to call RaisePropertyChanged on the UI thread:

DispatcherHelper.CheckBeginInvokeOnUI(
    () => RaisePropertyChanged(PowerStatePropertyName)
);

DispatcherHelper.BeginInvokeOnUl expects an Action so you can use any code in here just use

DispatcherHelper.CheckBeginInvokeOnUI(
    () => { /* complex code goes in here */ }
);

to do more complex tasks.

like image 67
AxelEckenberger Avatar answered Nov 05 '22 08:11

AxelEckenberger