2013-05-15 236 views
2

我正尝试在Windows服务中使用计时器。该服务能够启动和停止,并且在发生这种情况时我会向事件日志写入内容,这是有效的。我的问题是,我也想使用一个定时器,每次timeElapsed事件被触发时,定时器都会继续运行并向事件日志写入内容。在长时间运行的Windows服务中使用计时器

编辑:(我改变了代码,因此定时器是一个场,但依然没有结果,我所期望的,在事件日志中没有日志项)

using System.Timers; 

初始化服务:

public Timer timer; 

    public MonitorService() 
    { 
     InitializeComponent(); 
     timer = new Timer(10000); 
     //Some code that really doesn't matter 
    } 

上启动事件

protected override void OnStart(string[] args) 
    { 
     // Hook up the Elapsed event for the timer. 
     timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
     timer.Enabled = true; 

     timer.Start(); 

     EventLogger.WriteEntry("Biztalk monitoring service started", EventLogEntryType.SuccessAudit); 

     // If the timer is declared in a long-running method, use 
     // KeepAlive to prevent garbage collection from occurring 
     // before the method ends. 
     // GC.KeepAlive(timer); 
    } 


    private int count =0; 

上定时事件: (这是什么都不行,没有写入事件日志条目每隔10秒,而我希望它做的事)

// Specify what you want to happen when the Elapsed event is 
    // raised. 
    private void OnTimedEvent(object source, ElapsedEventArgs e) 
    { 
     //Some other code that doesn't mather 
     count++; 
     EventLogger.WriteEntry(string.Format("TimerEvent has ran {0} times. Total time is: {1}", count, e.SignalTime), EventLogEntryType.Information); 
    } 

的上停止事件:

protected override void OnStop() 
    { 
     EventLogger.WriteEntry("Biztalk monitoring service stopped", EventLogEntryType.Warning); 
    } 

主要

对于那些谁不知道这是我在Program.cs的主要方法:

 ///<summary> 
    ///The main entry point for the application. 
    ///</summary> 
    static void Main() 
    { 
     var servicesToRun = new ServiceBase[] 
      { 
       new MonitorService() 
      }; 
     ServiceBase.Run(servicesToRun); 
    } 

已经要求?确实是的!

我知道的事实,这个问题在前面已经喜欢这里问:Windows service with timerBest Timer for using in a Windows service

但是这些解决方案似乎并没有解决我的问题。

欢迎任何建议!

+1

我强烈建议你不要使用'System.Timers.Timer',因为它会吞噬异常,隐藏错误。如果您的Elapsed事件发生异常,您永远不会知道。请参阅http:// blog。mischel.com/2011/05/19/swallowing-exceptions-is-hiding-bugs/。你应该1)用'try/catch'保护你的事件处理程序,2)使用'System.Threading.Timer'。 –

+0

@JimMischel我刚刚发现这实际上是我的问题,现在我看到您的评论。它只是吞下一个例外,因为它没有奏效。 System.Threading.Timer是否修复了这一切? –

+0

'System.Threading.Timer'不会吞下异常,这会让您知道您的处理程序中有问题。真正的解决方案是非常小心地处理你的定时器事件处理程序中的异常。 –

回答

5

您的计时器在OnStart方法中是本地的。它不应该。它应该是你的服务类的一个字段,所以你不需要使用提示来欺骗垃圾收集器。

编辑: 您没有指定您的using s。确保使用Timer您正在使用System.Timers.Timer,而不是System.Windows.Forms.Timer

+0

噢,你说得对,甚至没有注意到,而专注于其他可能的错误的东西!去试试吧! –

+0

我用你的解决方案编辑了我的问题,但它仍然不起作用。 –

+0

我非常肯定我正在使用那个,我将它添加到我的问题 –

0

如果您想要在设定的时间段内记录事件日志(除了您正在使用的计时器已过去的事件),您可以使用服务级别的另一个计时器并注册已过去的时间事件。在这种情况下,你可以记录任何你想要的。

正如nvoigt所提到的,您应该将此计时器移至服务级别。