从c#中的不同线程启动一个计时器

嗨我已经介入了一些与计时器相关的问题。 希望有人可以帮忙..

  1. 我有一个包含按钮的窗体
  2. 当我点击该按钮时,我启动参数化线程
Thread thread1 = new Thread(new ParameterizedThreadStart( execute2)); thread1.Start(externalFileParams); 
  1. 线程内的代码执行得很好
  2. 在这个线程的最后一行,我启动一个计时器

 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但是没有触发计时器的tick事件

我正在研究VS2008 3.5框架。 我已经从工具箱拖动计时器并将其Interval设置为300也尝试设置Enabled true / false方法是timer1_Tick(Object sender , EventArgs e)但是它没有被触发

任何人都可以建议我做错了什么?

您可以尝试以这种方式启动计时器:

在表单构造函数中添加:

 System.Timers.Timer aTimer = new System.Timers.Timer(); aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Set the Interval to 1 second. aTimer.Interval = 1000; 

将此方法添加到Form 1:

  private static void OnTimedEvent(object source, ElapsedEventArgs e) { //do something with the timer } 

按钮点击事件添加:

 aTimer.Enabled = true; 

此计时器已经过线程化,因此无需启动新线程。

MatíasFidemraizer说的确如此。 但是,有一个工作…

如果您的表单上有一个可调用的控件(例如状态栏),则只需调用该控件即可!

C#代码示例:

 private void Form1_Load(object sender, EventArgs e) { Thread sampleThread = new Thread(delegate() { // Invoke your control like this this.statusStrip1.Invoke(new MethodInvoker(delegate() { timer1.Start(); })); }); sampleThread.Start(); } private void timer1_Tick(object sender, EventArgs e) { MessageBox.Show("I just ticked!"); } 

System.Windows.Forms.Timer在单线程应用程序中工作。

检查此链接:

备注说:

Timer用于以用户定义的间隔引发事件。 此Windows计时器专为使用UI线程执行处理的单线程环境而设计。 它要求用户代码具有可用的UI消息泵并且始终在同一线程中操作,或者将调用编组到另一个线程上。

阅读更多“备注”部分,您会发现Microsoft建议您使用此计时器将其与UI线程同步。

我会使用BackgroundWorker (而不是原始线程)。 主线程将订阅worker的RunWorkerCompleted事件 :当线程完成时,事件将在主线程中触发。 使用此事件处理程序重新启动计时器。