且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF 元素事件处理程序中的 UI 更新

更新时间:2023-01-25 23:21:53

使用 Dispatcher.BeginInvoke,您仍在为 LongTimeMethod() 使用 UI 线程.如果这不是必需的(即它正在执行某种后台处理),我建议使用 TPL 在后台线程上运行它:

With Dispatcher.BeginInvoke you are still using the UI thread for LongTimeMethod(). If this is not required (i.e. it is doing some kind of background processing) I would suggest using the TPL to run it on a background thread:

private void ButtonClick_EventHandler(object sender, RoutedEventArgs e)
{
    Label.Visibility = Visibility.Visible;
    TextBox.Text = "Processing...";

    Task.Factory.StartNew(() => LongTimeMethod())
        .ContinueWith(t =>
        {
            Dispatcher.BeginInvoke((Action)delegate()
            {
                TextBox.Text = "Done!";
            });
        });

}

使用此方法,长时间运行的方法在后台线程上处理(因此 UI 线程可以***地继续渲染,并且应用不会冻结)并且您可以执行任何改变 UI 的操作(例如后台任务完成时更新 UI Dispatcher 上的文本框文本

With this method, the long running method is processed on a background thread (so the UI thread will be free to keep rendering and the app won't freeze up) and you can do anything that does alter the UI (such as updating the textbox text) on the UI Dispatcher when the background task completes