Simple example of DispatcherHelper

妖精的绣舞 提交于 2019-11-28 11:25:46

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!