Wpf MVVM轻型线程示例
有没有关于如何使用MVVM Light的线程部分的示例?与普通的.net线程相比,使用MVVMLight.threading有什么优势?看起来MVVMLight中的所有线程部分都是此类:Wpf MVVM轻型线程示例,wpf,mvvm-light,wpf-4.0,Wpf,Mvvm Light,Wpf 4.0,有没有关于如何使用MVVM Light的线程部分的示例?与普通的.net线程相比,使用MVVMLight.threading有什么优势?看起来MVVMLight中的所有线程部分都是此类: public static class DispatcherHelper { public static Dispatcher UIDispatcher { get; private set; } /// <summary>
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
{
公共静态调度器
{
得到;
私人设置;
}
///
///在UI线程上执行操作。如果调用此方法
///从UI线程,立即执行操作
///方法,则该操作将排队
///在UI线程的调度程序上,并异步执行。
///对于UI线程上的其他操作,您可以获得
///由于该属性,对UI线程的调度程序的引用
/// .
///
///将在UI上执行的操作
///线。
公共静态无效检查BeginInvokeOnUI(操作)
{
if(UIDispatcher.CheckAccess())
{
动作();
}
其他的
{
UIDispatcher.BeginInvoke(操作);
}
}
///
///此方法应在UI线程上调用一次,以确保
///属性已初始化。
///在Silverlight应用程序中,在
///构建主页之后,应用程序启动事件处理程序。
///在WPF中,在静态App()构造函数上调用此方法。
///
公共静态void Initialize()
{
如果(UIDispatcher!=null)
{
返回;
}
//为了silverlight
UIDispatcher=Deployment.Current.Dispatcher;
//wpf
//IDispatcher=Dispatcher.CurrentDispatcher;
}
}
}
就这些。根据静态应用程序构造函数(wpf)或应用程序启动事件处理程序(Silverlight)中的注释使用DispatcherHelper.Initialize(),然后可以使用DispatcherHelper.CheckBeginInvokeOnUI(操作)
问候谢谢你。与普通的.net线程相比,它能在viewmodels中使用吗?1。首先,你初始化DispatcherHelper类调用initialize()方法——你必须在ui线程上这样做,这样它才能记住/设置它对dispatcher2的私有引用。之后,您可以使用DispatcherHelper.CheckBeginInvokeOnUI(操作操作)-从您想要的任何位置-查看、模型、视图模型-它将始终使用ui线程来调用您的操作3。关于正常的.net线程比较-通常情况下,你必须自己做这些事情:保持对ui调度程序的引用,检查ui线程上是否有u,最后调用dispatcher.BeginInvoke(action)-使用这个类会更容易