UI update in WPF elements event handlers

前端 未结 2 1646
萌比男神i
萌比男神i 2021-01-02 12:53

There is a problem with UI update in WPF.

I have such code:

    private void ButtonClick_EventHandler(object sender, RoutedEventArgs e)
    {
                


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-02 13:41

    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!";
                });
            });
    
    }
    

    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

提交回复
热议问题