大家在使用c#写windows服务时,网上很多例子说,使用工具箱中组件中的定时器就可以,但实际上该定时器并不管用,具体原因,微软自称是Framework的bug。

无论是windows窗体中timer还是组件中的timer都是继承自System.Windows.Form.Timer,并不是我们需要的System.Timers ,继承自System.Timers 的timer只有手动创建。

public WindowsServiceDemo()
        {
            InitializeComponent();
            System.Timers.Timer t = new System.Timers.Timer(1000);//实例化Timer类,设置间隔时间为10000毫秒; 
            t.Elapsed += new System.Timers.ElapsedEventHandler(TimeElapse);//到达时间的时候执行事件; 
            t.AutoReset = true;//设置是执行一次(false)还是一直执行(true); 
            t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
        }
public void TimeElapse(object source, System.Timers.ElapsedEventArgs e)
        {
            //EventLog log = new EventLog();
            //log.Source = "我的应用程序";
            //log.WriteEntry("1秒调用一次", EventLogEntryType.Information);
            FileStream fs = new FileStream(@"d:\timetick.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine("过了一秒 " + DateTime.Now.ToString() + "\n");
            m_streamWriter.Flush();
            m_streamWriter.Close();
            fs.Close();
 
        }

相关文章:

  • 2021-05-18
  • 2021-08-20
  • 2022-12-23
  • 2022-12-23
  • 2021-10-08
猜你喜欢
  • 2021-05-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-16
相关资源
相似解决方案