在用C# 开发个上位机界面,有个功能是对Test_Sequence()进行计时,请各位大神指点! 问题如下:
使用控件工具箱的Timer:
在面板上点击按钮,如果不运行Test_Sequence(),则可以在textBox2显示计时;但是调用Test_Sequence()后,计时器则无效,设置断点在计时溢出中没有响应。Test_Sequence() 是一个有限的循环,其中只有一些调用的函数和对DataGridview的显示操作。
private void BTN_TEST_Click(object sender, EventArgs e)
{
if (BTN_TEST.Text == "开始")
{
testtime = 0;
timer1.Interval = 100;
timer1.Enabled = true; //启动计时
BTN_TEST.Text = "停止";
//Test_Sequence();
}
else
{
BTN_TEST.Text = "开始";
timer1.Enabled = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
testtime += ((double)timer1.Interval/1000);
textBox2.Text = string.Format("{0:f1}", testtime);
}使用系统的Timer
System.Timers.Timer tc = new System.Timers.Timer();
tc.Interval = 100;
tc.Elapsed += new System.Timers.ElapsedEventHandler(tc_timeout); private void tc_timeout(object sender, EventArgs e)
{
testtime += ((double)tc.Interval / 1000);
textBox2.Text = string.Format("{0:f1}", testtime);
}
启动后在textBox2.Text中提示:线程间操作无效:不是从创建"TextBox2"的线程去访问它用C#一个月,觉得C#编程到处都是墙……………………
使用控件工具箱的Timer:
在面板上点击按钮,如果不运行Test_Sequence(),则可以在textBox2显示计时;但是调用Test_Sequence()后,计时器则无效,设置断点在计时溢出中没有响应。Test_Sequence() 是一个有限的循环,其中只有一些调用的函数和对DataGridview的显示操作。
private void BTN_TEST_Click(object sender, EventArgs e)
{
if (BTN_TEST.Text == "开始")
{
testtime = 0;
timer1.Interval = 100;
timer1.Enabled = true; //启动计时
BTN_TEST.Text = "停止";
//Test_Sequence();
}
else
{
BTN_TEST.Text = "开始";
timer1.Enabled = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
testtime += ((double)timer1.Interval/1000);
textBox2.Text = string.Format("{0:f1}", testtime);
}使用系统的Timer
System.Timers.Timer tc = new System.Timers.Timer();
tc.Interval = 100;
tc.Elapsed += new System.Timers.ElapsedEventHandler(tc_timeout); private void tc_timeout(object sender, EventArgs e)
{
testtime += ((double)tc.Interval / 1000);
textBox2.Text = string.Format("{0:f1}", testtime);
}
启动后在textBox2.Text中提示:线程间操作无效:不是从创建"TextBox2"的线程去访问它用C#一个月,觉得C#编程到处都是墙……………………
http://www.cnblogs.com/zhili/archive/2013/05/10/APM.html
我是用委托的方法处理的
private delegate void tc1fun();
.....
if (textBox2.InvokeRequired)
{
tc1fun tf = new tc1fun(updatetext2); //线程中使用委托
this.Invoke(tf);
} private void updatetext2()
{
textBox2.Text = string.Format("{0:f1}", testtime);
}