Home >Backend Development >C++ >How to Update a WPF UI from a Separate Thread in a Different Class?
Q: How to update a WPF UI from a worker thread running in a separate class?
A: To update the UI from a different thread:
Event-Based Communication:
Example Using Events:
// 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()); } }
Additional Note:
Alternative Solution Using Task:
In .NET 4.5 and later, you can also use asynchronous programming with Task to update the UI in a cleaner and more efficient way.
Updated Code Using Task:
// 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 */ })); } }
The above is the detailed content of How to Update a WPF UI from a Separate Thread in a Different Class?. For more information, please follow other related articles on the PHP Chinese website!