System.Timers.Timer running inconsitently in a Windows Service

May 6 2008 9:00 AM
Hi! I hope this is the right place to post this question, under multithreading. (There's no Service forum)

I am writing a windows service that does some cool stuff like getting http requests from a special report and launching background workers to do stuff asynchonously. However, I am getting really inconsitent results because of System.Timers.Timer.

Example:

In my service I define:
public System.Timers.Timer testTimer = new System.Timers.Timer(100);

and then I initialize it in OnStart with the following:

testTimer.Enabled = true;
testTimer.Elapsed += new System.Timers.ElapsedEventHandler(testTimer_Elapsed);


writeDbgTxt simply appends to a text file, like this:

void testTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
 writeDbgTxt("elapsed!");
}

public static void writeDbgTxt(string txt)
        {
            //TextWriter tw = new StreamWriter(@"C:\debug.txt");
            StreamWriter tw = System.IO.File.AppendText(@"C:\debug.txt");
            txt = DateTime.Now.ToString() + " ==> " + txt;
            tw.WriteLine(txt);
            tw.Flush();
            tw.Close();
        }


Now, I could expect to get ten lines written to disc every second, right? No. Instead I get really bogus results... anywhere from 0-10 lines written per second, and then after a while I stop getting any new lines at all. I know my service is still working because I can send it requests via http and it responds properly, but it's like that timer died.

Any ideas what's going wrong here?

Cheers,
N

Answers (2)