gpt4 book ai didi

multithreading - Win RT Metro C# MVVM 从工作线程更新 UI

转载 作者:行者123 更新时间:2023-12-03 10:20:18 25 4
gpt4 key购买 nike

我有 worker 类

public event EventHandler<EventArgs> DataModified;

可以从 UI 线程以外的地方引发(它是从服务器获取更新的网络客户端)。
我有 ModelView
ObservableCollection<DataModel> DataItems;

View 绑定(bind)到的。我的模型 View 必须订阅 ModifiedEvent,这样才能反射(reflect) DataItems 的变化。如何从回调事件更新 DataItems?我无法从我的模型 View 访问 UI Dispatcher(因为 View 不应该知道模型 View )。处理此问题的正确 .NET 4.5 方法是什么?

最佳答案

您可以创建一个拥有 CoreDispatcher 的服务并注入(inject)您的 View 模型(或使其成为静态)

public static class SmartDispatcher
{
private static CoreDispatcher _instance;
private static void RequireInstance()
{
try
{
_instance = Window.Current.CoreWindow.Dispatcher;

}
catch (Exception e)
{
throw new InvalidOperationException("The first time SmartDispatcher is used must be from a user interface thread. Consider having the application call Initialize, with or without an instance.", e);
}

if (_instance == null)
{
throw new InvalidOperationException("Unable to find a suitable Dispatcher instance.");
}
}

public static void Initialize(CoreDispatcher dispatcher)
{
if (dispatcher == null)
{
throw new ArgumentNullException("dispatcher");
}

_instance = dispatcher;
}

public static bool CheckAccess()
{
if (_instance == null)
{
RequireInstance();
}
return _instance.HasThreadAccess;
}

public static void BeginInvoke(Action a)
{
if (_instance == null)
{
RequireInstance();
}

// If the current thread is the user interface thread, skip the
// dispatcher and directly invoke the Action.
if (CheckAccess())
{
a();
}
else
{
_instance.RunAsync(CoreDispatcherPriority.Normal, () => { a(); });
}
}
}

您应该在 App.xaml.cs 中初始化 SmartDispatcher:
 var rootFrame = new Frame();
SmartDispatcher.Initialize(rootFrame.Dispatcher);

Window.Current.Content = rootFrame;
Window.Current.Activate();

以这种方式使用它:
SmartDispatcher.BeginInvoke(() => _collection.Add(item));

本类(class)基于 Jeff Wilcox's analog for windows phone 7 .

关于multithreading - Win RT Metro C# MVVM 从工作线程更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12351501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com