WPF Dispatcher.Invoke()和Dispatcher.BeginInvoke()

Dispatcher.Invoke()

用于同步执行消息。它确保在调用该方法时,当前线程上的消息队列中的消息会被依次处理。使用Invoke方法时,当前线程会阻塞,直到指定的消息被处理完毕。

Dispatcher.BeginInvoke()

用于异步执行消息。它允许将消息委托给指定的线程池来处理,从而避免了阻塞当前线程。该方法接受一个代表操作的对象和一个可选的超时时间。使用BeginInvoke方法时,消息将立即传递给线程池处理,而不会等待操作完成。

        
        private void Button_Click(object sender, RoutedEventArgs e)
        {
             Student student= Student(); 
             student.Name='张三';
             student.ClassName='1908C';

             Thread thread = new Thread(new ParameterizedThreadStart(CheckStoreInfo));
             thread.IsBackground = true;
             thread.Start(student);

        }

        //在线程里是无法直接操作Ui控件和打开新窗口的。
        public void CheckStoreInfo(object o)
        {
            Student model = (Student)o;
            //方法一
            Action action = () =>
            {
                txtStoreNo.Text = "1703A";
                TipWindow tip = new TipWindow();
                tip.Show();
            };

            //方法二
            Dispatcher.BeginInvoke(new Action(() => {
                txtStoreNo.Text = "1703B";
            }));
        
            //方法三
            //App.Current.Dispatcher.BeginInvoke(new Action<string>(ShowTip_Dialog),"登录成功!");
            
            //方法四 有参有返回值
            int param1 = 1,param2 = 2;
            object obj1 = Dispatcher.Invoke(new Func<int,int,int>(show),param1,param2)
        }

        public int show(int i, int k)
        {
            txtName.Text = "测试";
            return i+k;
        }

        public void ShowTip_Dialog(string info)
        {
            TipWindow tip = new TipWindow();
            tip.txtName.Text = tip.Name;
            tip.txtClassName.Text = tip.ClassName;
            tip.Show();
        }
        public class Student
        {
            public int ID { get; set; }
            public string Name { get; set; }
            public string ClassName { get; set; }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值