读书人

c# 计时器应用!

发布时间: 2013-09-13 21:12:00 作者: rapoo

c# 计时器应用求助!~!!~
在用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#编程到处都是墙……………………
[解决办法]
本帖最后由 caozhy 于 2013-09-08 12:15:01 编辑 System.Timers.Timer和System.Windows.Forms.Timer不同,它是基于线程的。

其实线程间操作无效:不是从创建"TextBox2"的线程去访问它这个提示很清楚了。

你需要用
this.Invoke(() => textBox2.Text = string.Format("{0:f1}", testtime));
[解决办法]
this.Dispatcher.Invoke(new Action(()=>textBox2.Text = string.Format("{0:f1}", testtime));

读书人网 >C#

热点推荐