問:如何從在單獨類別中執行的工作執行緒更新 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 及更高版本中,您也可以使用Task的非同步程式設計來以更乾淨、更有效率的方式更新 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中文網其他相關文章!