Search code examples
c#loggingwindows-servicesevent-log

Windows Service will not write to log file in loop


I am writing my first windows service and to start with it's just writing to a log file, which is working perfectly. I actually need the service to loop through the entries in a json file, which I have used elsewhere with no issues. So my service initiates a timer, and fires an event every 60 seconds;

System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 60000; // 60 seconds  
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
timer.Start();

This works absolutely perfectly and my OnTimer event is thus;

public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
    {
        eventLog1.WriteEntry("Drive Space monitoring initiated", EventLogEntryType.Information, eventId++);
    }

This puts the entry in the log exactly as I expect every 60 seconds. My problem comes when I try to add a loop to the OnTimer event. For simplicity, here is what I added;

int count = 4;
for(int x = 1; x <= count; x++)
{
    string msg = "This is just a counter: " + x.ToString();
    eventLog1.WriteEntry(msg, EventLogEntryType.Information, eventId++);
}

This has absolutely no effect and no further entries are added to my log file when the OnTimer event fires.


Solution

  • Use System.Threading.Timer instead of System.Timers.Timer.

    System.Timers.Timer gives issue some time when used in windows service and it will swallow all the exceptions.