WPF学习笔记2——WPF子线程更新UI

WPF学习笔记2——WPF子线程更新UI

1.Dispatcher

WPF应用程序的主线程负责创建UI界面、接收输入、处理事件等任务,在开发中常用子线程处理一些耗时的操作(为了主线程能及时响应,防止假死),但是子线程是不能直接更新UI界面。Dispatcher的作用是管理线程工作项队列,我们可以使用Dispatcher更新UI界面。

2.使用Dispatcher更新UI界面

下面是一个简单的例子,在子线程直接更新主线程维护的界面。

using System;
using System.Threading;
using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Thread thread = new Thread(ModifyLabel);
            lblShow.Content = "开始工作";
            thread.Start();
        }

        private void ModifyLabel()
        {
            // 模拟工作正在进行
            Thread.Sleep(TimeSpan.FromSeconds(2));
            lblShow.Content = "结束工作";
        }
    }
}

错误截图:

 

在子线程中使用Dispatcher.BeginInvoke()方法更新UI。

using System;
using System.Threading;
using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Thread thread = new Thread(ModifyLabel);
            lblShow.Content = "开始工作";
            thread.Start();
        }

        private void ModifyLabel()
        {
            // 模拟工作正在进行
            Thread.Sleep(TimeSpan.FromSeconds(2));

            //子线程更新UI线程可以使用Dispatcher.BeginInvoke()或者Invoke()方法。
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                //更新操作
                lblShow.Content = "结束工作";
            }));
        }
    }
}

 

子线程更新UI可以使用Dispatcher.BeginInvoke()或者Invoke()方法,Dispatcher.Invoke()是同步执行

 

posted @ 2020-07-06 20:50  落叶窥秋  阅读(1728)  评论(0编辑  收藏  举报