原代码:
程序代码
private void button1_Click(object sender, EventArgs e)
{
Thread cha = new Thread(new ThreadStart(DoPay));
System.Timers.Timer t=new System.Timers.Timer(5000);
t.Elapsed += new ElapsedEventHandler(DoPay);
t.AutoReset = true;
t.Enabled = true;
}
private void DoPay(object sender, ElapsedEventArgs e)
{
messageout.Text = "test";
}
执行时会报无法跨线程访问 messageout 控件
修改方法:
程序代码
private void button1_Click(object sender, EventArgs e)
{
System.Timers.Timer t=new System.Timers.Timer(5000);
t.Elapsed += new ElapsedEventHandler(threadDoPay);
t.AutoReset = true;
t.Enabled = true;
}
private void threadDoPay(object sender, ElapsedEventArgs e)
{
MethodInvoker mi = new MethodInvoker(DoPay);
this.BeginInvoke(mi);
}
private void DoPay()
{
messageout.Text = "test";
}