从 C# 中的不同线程启动计时器
您好,我遇到了一些与计时器相关的问题。 希望有人可以提供帮助..
- 我有一个包含按钮的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 但计时器的滴答事件没有被触发
我正在 VS2008 3.5 框架上工作。我已从工具箱中拖动计时器并将其 Interval
设置为 300 还尝试设置 Enabled
true/false 方法是 timer1_Tick(Object sender , EventArgs e)
但它没有被触发
有人可以建议我做错了什么吗?
Hi i have stepped into some problem related to timer.
hope somebody can help..
- I have a windows form containing a button
- when i click on that button i start a parameterised thread
Thread thread1 = new Thread(new ParameterizedThreadStart( execute2));
thread1.Start(externalFileParams);
- the code inside the thread executes very well
- at the last line of this thread i start a timer
.
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 but the tick event of the timer is not fired
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以尝试以这种方式启动计时器:
在表单构造函数中添加此方法:
将此方法添加到 Form1:
在按钮单击事件上添加此方法:
此计时器已经是线程化的,因此无需启动新线程。
You could try to start the timer this way:
Add in form constructor this:
Add this method to Form1:
On button click event add this:
This timer is already threaded so no need to start a new thread.
Matías Fidemraizer 所说的确实如此。但是,有一种解决方法......
当您的表单上有一个可调用的控件(例如状态栏)时,只需调用该控件即可!
C# 代码示例:
It is true what Matías Fidemraizer says. But, there is a work around...
When you have a control on your form that is invokable (eg. a statusbar), just invoke that one!
C# Code sample:
System.Windows.Forms.Timer 在单线程应用程序中工作。
检查此链接:
备注说:
阅读更多“备注”部分,您会发现微软建议您使用此计时器将其与UI线程同步。
System.Windows.Forms.Timer works in a single-threaded application.
Check this link:
Remarks says:
Read more "Remarks" section and you'll find that Microsoft recommends that you use this timer synchronizing it with the UI thread.
我会使用 BackgroundWorker (而不是 原始线程)。主线程将订阅工作线程的 RunWorkerCompleted 事件:当线程完成时,该事件在主线程中触发。使用此事件处理程序重新启动计时器。
I would use a BackgroundWorker (instead of a raw thread). The main thread would subscribe to the worker's RunWorkerCompleted event: The event fires in your main thread when the thread completes. Use this event handler to restart your timer.