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 メソッドで作成されるので、dispatcher は問題ないと思います。
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
ViewModel のいくつかのプロパティを変更することを除いて、何もしない 1 つのメソッドでイベントをサブスクライブします。したがって、スレッドは他のスレッドのオブジェクトを使用しないと確信しており、なぜこのエラーが発生するのかわかりません。私は何を間違っていますか?:(