Problem Statement:
In a multi-threaded WPF application, there's a need to update the UI from a background thread running in a separate class. The goal is to keep the UI responsive while lengthy calculations are being performed.
Solution using Event Dispatching:
Example Code:
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); } } }
Advantages of Event Dispatching:
The above is the detailed content of How to Safely Update a WPF UI from a Separate Background Thread?. For more information, please follow other related articles on the PHP Chinese website!