2013-10-20 51 views
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事件中一個方法,什麼也不做,只是在視圖模型改變某些屬性。因此,我確信線程不會使用其他線程的對象,我無法弄清楚爲什麼會出現此錯誤。我究竟做錯了什麼? :(

回答

0

誤差必須在此行 -

_visualNovels = _repository.GetAll(); 

您正在嘗試設置從後臺線程_visualNovels和我懷疑這是綁定到一些DP在你的GUI所以,你應該把這個電話UI Dispatcher爲好。

但是,我強烈建議你在地方定時器的使用DispatcherTimer。它是爲WPF創建的。

+1

唉,你是對的。該死的,我相信它的高時間休息一下我剛搬了這裏在調度程序的invoke方法內,它現在全部運行。謝謝你的時間:) – Kreweta

+0

很高興提供幫助。 :) –