从 C# 中的不同线程启动计时器 [英] start a timer from different thread in c#
问题描述
我遇到了一些与计时器相关的问题.希望有人能帮忙..
Hi i have stepped into some problem related to timer. hope somebody can help..
- 我有一个包含按钮的 Windows 窗体
- 当我点击那个按钮时,我会启动一个参数化线程
Thread thread1 = new Thread(new ParameterizedThreadStart( execute2));
thread1.Start(externalFileParams);
- 线程内部的代码执行得很好
- 在这个线程的最后一行,我启动了一个计时器
.
public void execute2(Object ob)
{
if (ob is ExternalFileParams)
{
if (boolean_variable== true)
executeMyMethod();//this also executes very well if condition is true
else
{
timer1.enabled = true;
timer1.start();
}
}
}
}
5 但定时器的滴答事件没有被触发
5 but the tick event of the timer is not fired
我正在研究 VS2008 3.5 框架.我已从工具箱中拖出计时器并将其 Interval
设置为 300 还尝试将 Enabled
设置为 true/false方法是 timer1_Tick(Object sender , EventArgs e)
但它没有被触发
I am working on VS2008 3.5 framework. I have dragged the timer from toolbox and set its Interval
to 300 also tried to set Enabled
true/false
method is timer1_Tick(Object sender , EventArgs e)
but its not fired
有人可以建议我做错了什么吗?
can anybody suggest what I am doing wrong?
推荐答案
您可以尝试以这种方式启动计时器:
You could try to start the timer this way:
在表单构造函数中添加:
Add in form constructor this:
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 1 second.
aTimer.Interval = 1000;
将此方法添加到Form1:
Add this method to Form1:
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
//do something with the timer
}
在按钮点击事件上添加:
On button click event add this:
aTimer.Enabled = true;
这个计时器已经被线程化了,所以不需要开始一个新的线程.
This timer is already threaded so no need to start a new thread.
这篇关于从 C# 中的不同线程启动计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!