计时器和 Windows 服务 c#

Timer and a Windows Serice c#

我在 Windows 服务中遇到了计时器的奇怪问题。是我的第一个 windows 服务,所以为了开始学习,我决定创建一个服务,每 10 秒在 .txt 文件中写入现在的时间。 我添加了计时器,但看起来计时器从未启动。 你能帮我理解我哪里错了吗? 这是我的代码:

namespace testtimer
{
    public partial class TestTimer : ServiceBase
    {
        public TestTimer()
        {
            InitializeComponent();
            timer.Interval = 10000;
            timer.Enabled = true;
        }

        protected override void OnStart(string[] args)
        {
            timer.Start();
        }

        protected override void OnStop()
        {
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            string date = System.DateTime.Now.ToString();
            StreamWriter wr = new StreamWriter(@"C:\Users\xxx\Desktop\Test\testtimer.txt", true);

            wr.WriteLine("\n" + "The Time is:" + "\t" + date);
            wr.Close();
        }
    }
}

我哪里错了?

非常感谢您的帮助:)

我猜你正在使用一个 Windows.Forms 定时器(组件一,你拖到你的设计表面上)......这需要一个 "window" 和 "message loop" 顺序能够 process/receive 实际的计时器滴答事件。

如果您是 NT 服务....您没有 window...您只是一段代码,其中包含由 SCM 调用的入口点(服务控制管理器)。

您需要使用不同类型的计时器,它使用线程,并将回调一个函数。

  • Best Timer for using in a Windows service