您可以创建一个包含 a 的服务CoreDispatcher
并将其注入您的视图模型(或使其成为静态)
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));
本课程基于Jeff Wilcox 的 windows phone 7 模拟。