当我试图在我的 WTF 应用程序中实现自动更新机制时,我在方法的Must create DependencySource on same Thread as the DependencyObject.
某处遇到了运行时错误。OnPropertyChanged()
我知道 WPF 应用程序是 STA,我应该使用调度程序,但这仍然无济于事:(
更详细...
我有一个服务类,它在构造函数中设置了一个计时器来执行更新
public VisualNovelService(IVisualNovelRepository repository, TimeSpan autoUpdateInterval)
{
this._repository = repository;
this._autoUpdateInterval = autoUpdateInterval;
this._visualNovels = _repository.GetAll();
this._autoUpdateTimer = new Timer(
(state) => Update(),
null,
TimeSpan.FromSeconds(3), // just so that I can test it,
Timeout.InfiniteTimeSpan);
this._dispatcher = Dispatcher.CurrentDispatcher;
}
对象本身是在 OnStartup 方法中创建的,因此我相信调度程序一切正常。
protected override void OnStartup(StartupEventArgs e)
{
Application.Current.Properties["VisualNovelService"] = new VisualNovelService(new FuwaVNRepository());
var viewModel = new MainWindowViewModel();
MainWindow.DataContext = viewModel;
MainWindow.Show();
}
这是一个更新方法,这是我代码中的恐怖分子:(
public event EventHandler<VisualNovelServiceEventArgs> Updated;
public void Update()
{
_visualNovels = _repository.GetAll();
// restart the autoupdate timer
_autoUpdateTimer.Change(_autoUpdateInterval, Timeout.InfiniteTimeSpan);
// raise the event
_dispatcher.Invoke(
() => Updated(this, new VisualNovelServiceEventArgs(_visualNovels)));
}
除了更改 ViewModel 中的某些属性外,我确实以一种什么都不做的方法订阅了该Updated
事件。因此,我确信线程不使用其他线程的对象,我无法弄清楚为什么会出现此错误。我究竟做错了什么?:(