Simple DispatcherHelper Example

I am trying to figure out how to use the DispatcherHelperftom MVVM light utility in SL, but I can not find any example.

From the home page of this structure, I know that

DispatcherHelper class, a lightweight class that helps you create multi-threaded applications.

But I do not know how to use it.

How and why can I use it?

+6
source share
1 answer

You only need DispatcherHelper when you want to make changes to the components of your UI thread, starting with code that runs in another thread. For instance. in a Silverlight application, you call a web service to retrieve some data asynchronously and now want to tell Ui that the data is present through the OnNotifyPropertyChanged event.

You must 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, initialization is done in the static constructor of the App class:

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

Then in your case, handling the completion of your asnc call, use the following code to call RaisePropertyChanged in the user interface thread:

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

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

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

to perform more complex tasks.

+17
source

Source: https://habr.com/ru/post/897226/


All Articles