所谓的潇洒

导航

子线程更新界面文本

当在线程中处理完一个事情,需要将结果反馈给界面时,如果直接修改界面文本就会报“在不是创建它的线程中访问控件”的错。在此记录两个处理办法:

1.线程同步

  System.Threading.SynchronizationContext _SyncContext = new System.Threading.SynchronizationContext.Current;//主线程中定义

  private void UpdateLable(object o) => { myLabel.Text=(string)o;}//主线程中定义

  _SyncContext.Post(UpdateLable, "成功");//子线程中调用,微软文档上说,这是异步请求消息,也就是说会产生线程

2.子线程中Invoke

  System.Windows.Forms.MethodInvoker mi = new System.Windows.Forms.MethodInvoker(() =>{myLabel.Text=“成功”; });
       this.BeginInvoke(mi);

  注意:

    若子线程有个数组,比如string[] strs,那么如下写法中的i可能超出数组界限
                                int count = strs.Count();
                                for (int i = 0; i < count; i++)
                                {
                                    System.Windows.Forms.MethodInvoker mi = new System.Windows.Forms.MethodInvoker(() => {label.Text = strs[i];});
                                    this.BeginInvoke(mi);
                                }

    正确写法

           int count = strs.Count();
                                for (int i = 0; i < count; i++)
                                {
                                    string text = nodes[i];
                                    System.Windows.Forms.MethodInvoker mi = new System.Windows.Forms.MethodInvoker(() => {label.Text = text;});
                                    this.BeginInvoke(mi);
                                }

    如果需要大量的这种写法,建议用Invoke代替BeginInvoke,因为BeginInvoke是异步的,会产生线程,Invoke写法如下

        this.Invoke((System.Windows.Forms.MethodInvoker)delegate { label.Text = text;});

posted on 2020-06-15 16:45  所谓的潇洒  阅读(172)  评论(0编辑  收藏  举报