线程内给窗体控件赋值

 两种方法(做个记录)

1使用delegate

      private delegate void SetTextDelegate(TextBox tb, Form form, string str);

   public void SetText(TextBox tb,Form form,string str) {if (form.InvokeRequired) { form.Invoke(new SetTextDelegate(setText), tb, form, str); } else { tb.Text = str; } }

2使用Action或者Func(推荐使用这个)

     private void setText(Form f,Control c,string str)
        {
            if (f.InvokeRequired) { f.Invoke(new Action<Form, Control, string>(setText),f,c,str); }
            else { c.Text = str; }
        }
      public Action<Control, Form, string> setText;
        public void SetText(Control tb, Form form, string str)
        {
            setText += SetText; #绑定方法
       setText += ceshi;  #绑定另一个方法 if (form.InvokeRequired) { form.Invoke(setText, tb, form, str); } else { tb.Text = str; } }
public void ceshi(Control tb, Form form, string str) { if (form.InvokeRequired) { form.Invoke(setText, textBox2, form, str); } else { textBox2.Text = str; } }
  public void CC()
        {
            Task.Run(()=>
            {
                SetText(textBox1, this, "啦啦");
            }); 
            
        }

会同时给textbox1与textbox2赋值"啦啦"

原文地址:https://www.cnblogs.com/ningxinjie/p/12610436.html