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 WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private delegate void test(string str);
private void button1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(()=> {
string flag = "";
int i;
Thread.Sleep(5000);
flag = "asdf";
textBox1.Invoke(new test(testhandler1), flag);
for( i = 0; i < 6; i++)
{
Thread.Sleep(1000);
}
textBox2.BeginInvoke(new test(testhandler2), i.ToString() );
});
}
private void testhandler1(string str)
{
Thread.Sleep(5000);
textBox1.Text = str;
// textBox2.Text = str;
}
private void testhandler2(string str)
{
// Thread.Sleep(5000);
textBox2.Text = str;
}
}
}
控件的BeginInvoke方法可以保证在调用BeginInvoke的方法的线程异步方式运行委托的代码(testhandler)。
而Invoke方法是同步执行委托的方法(testhandler)