从启动不同的线程在C#中的计时器 [英] start a timer from different thread in c#

查看:468
本文介绍了从启动不同的线程在C#中的计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我已经步入相关定时器一些问题。
,希望有人能帮助..




  1. 我有一个包含一个按钮,Windows窗体

  2. 当我那个按钮点击我开始一个参数化的线程





 线程线程1 =新主题(新ParameterizedThreadStart(execute2)); 
thread1.Start(externalFileParams);




  1. 线程内的代码执行得非常好

  2. 在该线程的最后一行我启动一个定时器



 公共无效execute2(对象ob)
{
如果(OB是ExternalFileParams)
{
如果(boolean_variable ==真)
executeMyMethod(); //这也执行得很好,如果条件为真
,否则
{
timer1.enabled = TRUE;
timer1.start();
}
}
}
}



5但定时器的Tick事件不会触发



我的工作VS2008 3.5框架。我已经拖从工具箱中的定时器,并设置其间隔 300还试图设置已启用真/假
法是 timer1_Tick(对象发件人,EventArgs五),但它不是解雇



有谁能够表明我在做什么错


解决方案

结果
你可以尝试启动计时器这种方式:



添加在表单构造这样的:

  System.Timers.Timer aTimer =新System.Timers .Timer(); 
aTimer.Elapsed + =新ElapsedEventHandler(OnTimedEvent);
//设置的时间间隔为1秒。
aTimer.Interval = 1000;

这方法添加到Form1中:

 私有静态无效OnTimedEvent(对象源,ElapsedEventArgs E)
{
//使用计时器
的东西}

在按钮单击事件补充一点:

  aTimer.Enabled = TRUE; 

这计时器已经螺纹所以没有必要启动一个新线程。


Hi i have stepped into some problem related to timer. hope somebody can help..

  1. I have a windows form containing a button
  2. when i click on that button i start a parameterised thread

Thread thread1 = new Thread(new ParameterizedThreadStart( execute2));
thread1.Start(externalFileParams);

  1. the code inside the thread executes very well
  2. 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?

解决方案


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;

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆