UI update in WPF elements event handlers

自闭症网瘾萝莉.ら 提交于 2019-12-19 03:06:12

问题


There is a problem with UI update in WPF.

I have such code:

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

        LongTimeMethod(); //some long operation
    }

The problem is that until LongTimeMethod ends (that is event handler ends), Label.Visibility and TextBox.Text will not be changed.

I solved it like this so far:

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

        Dispatcher.BeginInvoke(new Action(LongTimeMethod), 
            DispatcherPriority.Background);
    }

Is there any other solution without using dispatcher invocation? Calling this.UpdateLayout() doesn't help.


回答1:


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




回答2:


Visibility and Text are dependency properties which updated by dispatcher. Your solution is absolutely corrent, but my suggestion is to do it asynchronously.

On other hand, you might simulate Application.DoEvents in WPF (see the article).



来源:https://stackoverflow.com/questions/6346088/ui-update-in-wpf-elements-event-handlers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!