5
有没有关于如何使用MVVM Light的线程部分的例子?在正常的.net线程中使用MVVMLight.threading有什么好处?MVVM光线程示例
有没有关于如何使用MVVM Light的线程部分的例子?在正常的.net线程中使用MVVMLight.threading有什么好处?MVVM光线程示例
看起来像mvvmlight所有线程部分是这个类:
public static class DispatcherHelper
{
public static Dispatcher UIDispatcher
{
get;
private set;
}
/// <summary>
/// Executes an action on the UI thread. If this method is called
/// from the UI thread, the action is executed immendiately. If the
/// method is called from another thread, the action will be enqueued
/// on the UI thread's dispatcher and executed asynchronously.
/// <para>For additional operations on the UI thread, you can get a
/// reference to the UI thread's dispatcher thanks to the property
/// <see cref="UIDispatcher" /></para>.
/// </summary>
/// <param name="action">The action that will be executed on the UI
/// thread.</param>
public static void CheckBeginInvokeOnUI(Action action)
{
if (UIDispatcher.CheckAccess())
{
action();
}
else
{
UIDispatcher.BeginInvoke(action);
}
}
/// <summary>
/// This method should be called once on the UI thread to ensure that
/// the <see cref="UIDispatcher" /> property is initialized.
/// <para>In a Silverlight application, call this method in the
/// Application_Startup event handler, after the MainPage is constructed.</para>
/// <para>In WPF, call this method on the static App() constructor.</para>
/// </summary>
public static void Initialize()
{
if (UIDispatcher != null)
{
return;
}
// for silverlight
UIDispatcher = Deployment.Current.Dispatcher;
// wpf
//IDispatcher = Dispatcher.CurrentDispatcher;
}
}
}
,这一切。使用DispatcherHelper.Initialize()根据静态构造应用程序(WPF)或Application_Startup事件处理程序(Silverlight的)评论 - 然后u可以使用DispatcherHelper.CheckBeginInvokeOnUI(动作动作)
问候
感谢agend。如何将它与普通的.net线程进行比较,并且可以在视图模型中使用它? – 2010-12-02 15:28:16
1.首先初始化DispatcherHelper类调用Initialize()方法 - 并且你必须在ui线程上做它,以便它可以记住/设置它对调度程序的私有引用。 – agend 2010-12-02 20:24:01
2.之后,你可以使用DispatcherHelper.CheckBeginInvokeOnUI(Action action) - 从任何你想要的地方 - 视图,模型,视图模型 - 它将始终使用ui线程来调用你的动作 3.关于正常的.net线程比较 - 通常你必须自己做这些事情:继续参考ui调度程序,检查你是否在ui线程上,最后调用dispatcher.BeginInvoke(action) - 这个类更容易 – agend 2010-12-02 20:30:14