线程内的计时器

时间:2010-06-29 10:28:36

标签: c# winforms multithreading timer

如何在一个简单的线程中启动forms.timer,我有一个问题  我需要在线程内启动计时器,我该怎么做

3 个答案:

答案 0 :(得分:2)

更好的选择是使用不需要消息循环的System.Timers.Timer类,看起来像Windows表单或者你可以直接使用System.Threading.Timer(如果你需要知道所有的这两个类之间的差异有a blog post with all the details):

using System;
using System.Threading;

class Program
{
    static void Main()
    {
        using (new Timer(state => Console.WriteLine(state), "Hi!", 0, 5 * 1000))
        {
            Thread.Sleep(60 * 1000);
        }
    }
}

如果你真的想要一个System.Windows.Forms.Timer工作,它需要一个消息循环,你可以使用Application.Run the parameter-less onethe one taking an ApplicationContext在一个线程中启动一个消息循环,以便更好地控制生命周期

using System;
using System.Windows.Forms;

class Program
{
    static void Main()
    {
        var timer = new Timer();
        var startTime = DateTime.Now;
        timer.Interval = 5000;
        timer.Tick += (s, e) =>
        {
            Console.WriteLine("Hi!");
            if (DateTime.Now - startTime > new TimeSpan(0, 1, 0))
            {
                Application.Exit();
            }
        };
        timer.Start();
        Application.Run();
    }
}

答案 1 :(得分:0)

当你使用线程时,你真的想使用System.Threading.Timer。

有关详细信息,请参阅此问题:Is there a timer class in C# that isn't in the Windows.Forms namespace?

答案 2 :(得分:0)

documentation说:

此计时器已针对Windows窗体应用程序进行了优化,必须在窗口中使用。

使用类似Thread.Sleep的东西。

相关问题