2017-10-08 11 views
2

私は動作しませんでした次のコードの部分を持っているなぜDispatcher.CurrentDispatcher.BeginInvokeを使用してもGUIは更新されませんが、BeginInvokeを使用するのはなぜですか?

BeginInvokeをDispatcher.CurrentDispatcher.BeginInvokeの違いについて混乱しています、UpdateCountsメソッドのコードは無視されている:

private void Start() 
{ 
    _testResults = new TestResults(ModelNameTextBox.Text); 
    _timer = new System.Threading.Timer(UpdateCounts, null, 0, 500);    
} 

private void UpdateCounts(object info) 
{ 
    Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() => 
    { 
     PassCountLabel.Text = _testResults.PassedCount.ToString(); 
     RequestCountLabel.Text = _testResults.RequestedCount.ToString();     
    })); 
} 

しかし、一度Dispatcher.CurrentDispatcherを取り除く、それが正常に動作します:

private void UpdateCounts(object info) 
{ 
    BeginInvoke(new Action(() => 
    { 
     PassCountLabel.Text = _testResults.PassedCount.ToString(); 
     RequestCountLabel.Text = _testResults.RequestedCount.ToString();     
    })); 
} 
+2

このようにWPFとWinformsのコードを任意に混在させることはできません。あなたのMain()エントリーポイントがWinformsバージョンのApplication.Run()を使用したようです。 Dispatcherを使用すると、アプリケーションにディスパッチャーループがないため、コードを実行できません。これが*意図的な*の場合、言い換えれば、このコードはライブラリにあり、ライブラリを使用するWPFまたはWinformsアプリケーションであるかどうかを想定することはできません。 SynchronizationContext.Currentをコンストラクタにコピーする必要があります。しかし、再びライブラリのコントロールを更新するのは悪いです。混同しないでください。 –

答えて

0

Dispatcher.CurrentDispatcher.BeginInvokeは、UIスレッドから呼び出す場合にのみ機能し、そうでない場合は現在のスレッドを呼び出します。

あなたはUIスレッドを呼び出すためにApplication.Current.Dispatcherを使用する必要があります。

関連する問題