这段代码为什么不能运行?子线程访问UI主线程的控件不能执行



```c#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace invoke1
{
    public delegate void MyInvoke(string str);
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        

        private void button9_Click(object sender, EventArgs e)
        {
            //_myInvoke = new MyInvoke(SetText);
            //CheckForIllegalCrossThreadCalls = false;
            Thread t = new Thread(new ThreadStart(fun));
            t.Start();
        }

        private void fun()
        {
            //_myInvoke("dddd");
            SetText("ddd");
        }
        private void SetText(string s)
        {
            if (textBox6.InvokeRequired)
            {
                MyInvoke _myInvoke = new MyInvoke(SetText);
                this.Invoke(_myInvoke, new object[] { s });
            }
            else
            {
                this.textBox6.Text = s;
            }
        }
    }


}

```

线程内委托执行textBox的修改比较好

private delegate void dvg(string s);

private void ceshiThread(Object obj)
{
    textBox1.Invoke(new dvg((s) => {
            textBox1.Text = s;
    }), new object[] { "你需要赋值的字符串" });
}

private void button1_Click(object sender, EventArgs e)
{
    Thread th = new Thread(ceshiThread);
    th.IsBackground = true;
    th.Start();
}

不能直接传fun 方法,要传当前对象的实例this, 在线程那边再调用fun 方法。

fun里面的 SetText(“ddd”) 改为 this.invoke(new MyInvoke(SetText), new object[] { "ddd" });