2017-04-26 30 views
0

我在Windows服务中遇到了计时器的奇怪问题。是我的第一个Windows服务,因此,为了开始学习,我决定创建一个服务,每10秒钟在一个.txt文件中写入什么时间。 我添加了计时器,但看起来像定时器永远不会启动。 你能帮我理解我错在哪里吗? 这里我的代码:计时器和Windows Serice c#

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(); 
     } 
    } 
} 

在那里我错了吗?

非常感谢您的帮助:)

+2

timer.Tick + = timer_Tick;也许? – linuxrocks

回答

1

猜你使用的是Windows.Forms定时器(组件之一,你拖到你的设计图面)......这就需要一个“窗口”和“消息循环“以便能够处理/接收实际的计时器滴答事件。

当你是一个NT服务....你没有一个窗口......你只是一些代码,它有SCM(服务控制管理器)调用的入口点。

您需要使用不同类型的使用线程的计时器,并且会回调函数。

+0

非常感谢!这就是为什么我在Windows窗体上测试相同的功能,并且在工作和服务中不...谢谢你的时间和你的帮助:).... Patrick –