繁体   English   中英

从C#中的其他线程启动计时器

[英]start a timer from different thread in c#

嗨,我已经涉足定时器相关的一些问题。 希望有人可以帮助..

  1. 我有一个包含按钮的Windows表单
  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,但未触发计时器的滴答事件

我正在研究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;

将此方法添加到Form1:

 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在单线程应用程序中工作。

检查此链接:

备注说:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM