public partial class Form1 : Form
{
private delegate void DelegateSetText(string text);
private void SetText(string text)
{
if (this.txtMessage.InvokeRequired)
{
Invoke(new DelegateSetText(SetText), text);
}
else
{
this.txtMessage.Text += text;
}
}
public Form1()
{
InitializeComponent();
//Control.CheckForIllegalCrossThreadCalls = false;
}
private void btnTest_Click(object sender, EventArgs e)
{
var t = Task.Factory.StartNew(() =>
{
Do();
});
}
private void Do()
{
btnTest.Invoke(new MethodInvoker(delegate() { btnTest.Enabled = false; }));
txtMessage.Invoke(new MethodInvoker(delegate() { txtMessage.Text = ""; }));
//this.Invoke(new MethodInvoker(() => { btnTest.Enabled = false; }));
//this.Invoke(new MethodInvoker(() => { txtMessage.Text = ""; }));
int i = 0;
while (i < 10)
{
string str = DateTime.Now + ":" + i + "\r\n";
// 简单代码直接写代理
txtMessage.Invoke(new MethodInvoker(delegate() { this.txtMessage.Text += str; }));
/////或者使用如下方法,显示声明代理
//SetText(str);
Thread.Sleep(1000);
i++;
}
btnTest.Invoke(new MethodInvoker(delegate() { btnTest.Enabled = true; }));
//this.Invoke(new MethodInvoker(() => { btnTest.Enabled = true; }));
/*
this.Invoke(new MethodInvoker(() =>
{
btnTest.Enabled = false;
txtMessage.Text = "";
int i = 0;
while (i < 10)
{
string str = DateTime.Now + ":" + i + "\r\n";
// 简单代码直接写代理
txtMessage.Invoke(new MethodInvoker(delegate() { this.txtMessage.Text += str; }));
/////或者使用如下方法,显示声明代理
//SetText(str);
Thread.Sleep(1000);
i++;
}
btnTest.Enabled = true;
}));
*/
}
}