问:如何从在单独类中运行的工作线程更新 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中文网其他相关文章!