0
虽然我试图在我的WTF应用程序中实现自动更新机制,但我在OnPropertyChanged()
方法中得到了运行时错误Must create DependencySource on same Thread as the DependencyObject.
。我知道WPF应用程序是STA,我应该使用调度,但仍然没有帮助:(System.Threading.Timer执行自动更新
更详细...
我已经设定在构造一个计时器服务类执行更新
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)));
}
我订阅Updated
事件中一个方法,什么也不做,只是在视图模型改变某些属性。因此,我确信线程不会使用其他线程的对象,我无法弄清楚为什么会出现此错误。我究竟做错了什么? :(
唉,你是对的。该死的,我相信它的高时间休息一下我刚搬了这里在调度程序的invoke方法内,它现在全部运行。谢谢你的时间:) – Kreweta
很高兴提供帮助。 :) –