WPF的Dispatcher类里的BeginInvoke,Invoke,InvokeAsync

原文地址:https://blog.csdn.net/niuge8905/article/details/81117989

深入了解 WPF Dispatcher 的工作原理(Invoke/InvokeAsync 部分)https://blog.csdn.net/WPwalter/article/details/78093917

这里主要用上几个实例。总结一下:

1.BeginInvoke和InvokeAsync原理一致,可取得一致的结果,用InvokeAsync会更实用方便,因为可以直接用上Action和Fun方法。

2.Invoke会阻塞线程,直到Invoke里的代码完成,InvokeAsync和BeginInvoke会直接运行后面的代码。

来看一个简单的实例:

        private void btnExecute_Click(object sender, RoutedEventArgs e)
        {
            Thread th = new Thread(DoSomething);
            th.Start();

            result.Content = "1";
            this.Dispatcher.Invoke(() => { result.Content += "2"; Thread.Sleep(2000); });
            result.Content += "3";
        }

        private void DoSomething()
        {
            for (int i = 0; i < 10; i++)
            {
                this.Dispatcher.Invoke(() => { result.Content += i.ToString(); });
                Thread.Sleep(1000);
            }
        }

修改按钮点击的 Invoke 为 InvokeAsync, 代码如下:

       private void btnExecute_Click(object sender, RoutedEventArgs e)
        {
            Thread th = new Thread(DoSomething);
            th.Start();

            result.Content = "1";
            this.Dispatcher.InvokeAsync(() => { result.Content += "2"; Thread.Sleep(2000); });
            result.Content += "3";
        }

        private void DoSomething()
        {
            for (int i = 0; i < 10; i++)
            {
                this.Dispatcher.Invoke(() => { result.Content += i.ToString(); });
                Thread.Sleep(1000);
            }
        }

执行结果:

InvokeAsync 不会等待工作线程结束,直接执行后面的代码,所以先运行了 result.Content += "3"

修改线程函数中的 Invoke 为 InvokeAsync,代码如下:

        private void btnExecute_Click(object sender, RoutedEventArgs e)
        {
            Thread th = new Thread(DoSomething);
            th.Start();

            result.Content = "1";
            this.Dispatcher.InvokeAsync(() => { result.Content += "2"; Thread.Sleep(2000); });
            result.Content += "3";
        }

        private void DoSomething()
        {
            for (int i = 0; i < 10; i++)
            {
                this.Dispatcher.InvokeAsync(() => { result.Content += i.ToString(); });
                Thread.Sleep(1000);
            }
        }

执行结果如下:

  

原文地址:https://www.cnblogs.com/runningRain/p/13724141.html