Q: 別のクラスで実行されているワーカー スレッドから WPF UI を更新するにはどうすればよいですか?
A: 別のから UI を更新するにはthread:
イベントベース通信:
イベントの使用例:
// Main window class private void startCalc(object sender, RoutedEventArgs e) { // Create a new worker class instance CalcClass calc = new CalcClass(); // Register event handler to receive UI update notifications calc.ProgressUpdate += (s, e) => { Dispatcher.Invoke((Action)(() => { /* Update UI here */ })); }; // Start the worker thread Thread calcThread = new Thread(new ParameterizedThreadStart(calc.TestMethod)); calcThread.Start(input); } // Worker class public class CalcClass { public event EventHandler ProgressUpdate; public void TestMethod(object input) { // Perform calculations // Raise event to notify UI update if (ProgressUpdate != null) ProgressUpdate(this, new EventArgs()); } }
補足:
を使用した代替解決策タスク:
.NET 4.5 以降では、タスクで非同期プログラミングを使用して、よりクリーンで効率的な方法で UI を更新することもできます。
タスクを使用してコードを更新しました:
// Main window class private async void buttonDoCalc_Clicked(object sender, EventArgs e) { // Create a new worker class instance CalcClass calc = new CalcClass(); // Start the asynchronous calculation await calc.CalcAsync(); } // Worker class public class CalcClass { public async Task CalcAsync() { // Perform calculations // Update UI using Dispatcher.Invoke Dispatcher.Invoke((Action)(() => { /* Update UI here */ })); } }
以上が別のクラスの別のスレッドから WPF UI を更新するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。