問題陳述:
在多執行緒WPF在應用程式中,需要從在單獨的類別中執行的後台執行緒更新UI。目標是在執行冗長的計算時保持 UI 回應。
使用事件調度的解決方案:
範例程式碼:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void startCalc(object sender, RoutedEventArgs e) { inputValues input = new inputValues(); calcClass calculations = new calcClass(); try { // Parse user inputs } catch { // Handle input errors } // Register event handler calculations.ProgressUpdate += OnProgressUpdate; // Start background calculations Thread calcthread = new Thread( new ParameterizedThreadStart(calculations.testMethod)); calcthread.Start(input); } private void OnProgressUpdate(object sender, YourEventArgs args) { Dispatcher.Invoke((Action)delegate() { // Update UI based on event arguments }); } } public class calcClass { public event EventHandler<YourEventArgs> ProgressUpdate; public void testmethod(inputValues input) { for (int i = 0; i < 1000; i++) { // Perform calculations // Raise ProgressUpdate event when needed if (ProgressUpdate != null) ProgressUpdate(this, new YourEventArgs(status)); Thread.Sleep(10); } } }
事件調度的優點:
以上是如何從單獨的後台執行緒安全地更新 WPF UI?的詳細內容。更多資訊請關注PHP中文網其他相關文章!