WPF多线程更改UI界面数据

public partial class MainWindow : Window
{

    private System.Windows.Threading.DispatcherTimer timer;
    public MainWindow()
    {
        InitializeComponent();
        timer = new System.Windows.Threading.DispatcherTimer();
        timer.Interval = TimeSpan.FromMilliseconds(1000);
        timer.Tick += timerTick;
        timer.Start();
    }

    private void timerTick(object sender, EventArgs e)
    {
        //WPF更改UI界面数据
        //解决方案:使用Dispatcher.BeginInvoke(委托方式{修改UI})

        //方案一:使用delegate
        /*this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)delegate ()
        {
            tbText.Text = Guid.NewGuid().ToString();
        });*/

        //方案二:Action
        this.Dispatcher.Invoke(new Action(() =>
        { tbText.Text = Guid.NewGuid().ToString(); }));
    }
}

  源码下载:WPFThread1.0

posted @ 2021-03-28 02:38  microsoft-zhcn  阅读(290)  评论(0编辑  收藏  举报