问题陈述:
在多线程 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中文网其他相关文章!