for*_*yez 16 c# wpf multithreading mvvm
所以说在MVVM环境中,我在后台线程中,我想在ui控件上运行更新.所以通常我会去myButton.Dispatcher.BeginInvoke(blabla),但我无法访问myButton(因为viewmodel无法访问视图的控件).那么这样做的正常模式是什么?
(我想总是有约束力,但我想通过调度员知道如何做到这一点)
Tho*_*que 37
我通常使用Application.Current.Dispatcher:因为Application.Current是静态的,所以不需要对控件的引用
Cat*_*ICU 15
来自Caliburn Micro源代码:
public static class Execute
{
private static Action<System.Action> executor = action => action();
/// <summary>
/// Initializes the framework using the current dispatcher.
/// </summary>
public static void InitializeWithDispatcher()
{
#if SILVERLIGHT
var dispatcher = Deployment.Current.Dispatcher;
#else
var dispatcher = Dispatcher.CurrentDispatcher;
#endif
executor = action =>{
if(dispatcher.CheckAccess())
action();
else dispatcher.BeginInvoke(action);
};
}
/// <summary>
/// Executes the action on the UI thread.
/// </summary>
/// <param name="action">The action to execute.</param>
public static void OnUIThread(this System.Action action)
{
executor(action);
}
}
Run Code Online (Sandbox Code Playgroud)
在使用之前,您必须Execute.InitializeWithDispatcher()从UI线程调用,然后您可以像这样使用它Execute.OnUIThread(()=>SomeMethod())
我倾向于让我的ViewModel继承自DependencyObject并确保它们是在UI线程上构建的,这使得它们能够完美地处理这种情况 - 它们具有Dispatcher与UI线程的调度程序相对应的属性.然后,您不需要使用ViewModel的实现细节污染您的视图.
其他一些优点:
Application.Current.Dispatcher)