委托有两种,一种是同步委托Invoke和异步委托BeginInvoke
举个例子,Form2要调用Form1使其的控件变化可以在Form2创建一个委托使其指向Form1的某个方法如下
Form1代码
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.testClick += SetTextBox;
form2.Show();
}
public void SetTextBox(string s)
{
textBox1.Text = s;
}
Form2代码
public delegate void test(string s);
public event test testClick;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string txt = textBox1.Text;
testClick.Invoke(txt);
}
这是两个窗体的方法,同窗体一般只会用到线程,异步线程不能控制UI线程,所以你要控制UI线程需要用到委托
如下
invokeThread线程无法使textBox1改变必须调用委托来使其改变
private Thread invokeThread;
private delegate void invokeDelegate();
private void StartMethod(){
Control.Invoke(new invokeDelegate(invokeMethod));
}
private void invokeMethod(){
textBox1.Text = “123”;
}
private void butInvoke_Click(object sender, EventArgs e) {
invokeThread = new Thread(new ThreadStart(StartMethod));
invokeThread.Start();
}