为什么下面的代码报错:
public partial class Form1 : Form
{
Thread t; public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{ } private void ThreadP()
{
textBox1.Text = "实现在子线程中操作主线程中的控件";
t.Abort();
} private void button1_Click(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(ThreadP));
t.Start();
}
}----用下面的代码却可以:
public partial class Form1 : Form
{
Thread t;
private delegate void SetText(); public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{ } private void ThreadP()
{
SetText d=new SetText(Threading);
this.Invoke(d);
} private void Threading()
{
textBox1.Text = "实现在子线程中操作主线程中的控件";
t.Abort();
} private void button1_Click(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(ThreadP));
t.Start();
}
}使用了delegate怎么就可以了呢?还有上面的"this",指的是窗体主线程吗?还是new 出来的那个线程呢?
public partial class Form1 : Form
{
Thread t; public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{ } private void ThreadP()
{
textBox1.Text = "实现在子线程中操作主线程中的控件";
t.Abort();
} private void button1_Click(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(ThreadP));
t.Start();
}
}----用下面的代码却可以:
public partial class Form1 : Form
{
Thread t;
private delegate void SetText(); public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{ } private void ThreadP()
{
SetText d=new SetText(Threading);
this.Invoke(d);
} private void Threading()
{
textBox1.Text = "实现在子线程中操作主线程中的控件";
t.Abort();
} private void button1_Click(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(ThreadP));
t.Start();
}
}使用了delegate怎么就可以了呢?还有上面的"this",指的是窗体主线程吗?还是new 出来的那个线程呢?
--------------
这里的this指的是子线程?
不就知道this是啥了吗
因为:“子线程 不能调用 主线程创建的 控件”
所以让窗体来Invoke调用线程的方法,
而窗体要调用子线程的方法,就要用delegate的方式。就当就是这样理解吧?