C# Windows Service Timer stopping

I have a C# windows service which uses a timer to check for files in a directory every second. If files exit then the timer_elapsed method stops the timer, processes the files and upon completion restarts the timer. The process then starts again.

The problem I am facing is that every now and then the timer does not work. The service is still running. I know that it is not a problem with the files as I have put them through outside of this project and they work. So I believe the issue is with the timer itself. It's very difficult to actually test for this because the timer just doesn't restart.

Here is my example code:

 private static System.Timers.Timer _timer;

_timer = new System.Timers.Timer();
_timer.Interval = 1000;
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start();
GC.KeepAlive(_timer);

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {  FileChecker();
}

public void FileChecker()
        {
            _timer.Stop();
string fileExtensions = "*.txt";
            
            DirectoryInfo myDirInfo = new DirectoryInfo(@"C:\Program Files (x86)\MyProgram\Process\");
    
            
            for (int i = 0; i <= fileExtensions.GetUpperBound(0); ++i)
            {
                FileInfo[] allFiles = myDirInfo.GetFiles(fileExtension);

                if (allFiles.Any())
                {
                    foreach (FileInfo f in allFiles)
                    {
                        string filePath = Convert.ToString(myDirInfo + f.ToString());                        
                        FileReader myFileReader = new FileReader ();
                        myFileReader .SetFilePath = filePath;
                        myFileReader .ReadFile();

                        File.Delete(filePath);
                                      
                    }
                }
            }
            
            _timer.Start();
        }

Open in new window


I was hoping somewhere someone can give me an idea on what the problem I am facing is and possible steps I need to resolve it.

Thank you.
kbussAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
lenordisteConnect With a Mentor Commented:
Hi,

you should probably change your code to something like this to ensure in case of an exception that your timer gets restarted properly:
try{
_timer.Stop();
string fileExtensions = "*.txt";
//rest of your code
}
finally{
_timer.Start();
}

Open in new window


Also, there s a well known bug regarding timers in services in .NET 1.1 which you may be using. Information and hotfix are here:
http://support.microsoft.com/kb/842793/en-us
0
 
kbussAuthor Commented:
Im using .NET 4. I've got anitvirus on my web/database server. I wonder if this could be causing some sort of disruption. What a nightmare. I was hoping to come across someone who had run into this problem before.
0
 
kbussAuthor Commented:
Ok the whole antivirus thing was a load of old bong. I knew it was, just was a coincidence. I was clutching at straws.

Right, the try, finally seems to be what I'am looking for. It has forced my timer to restart and therefore keeps the program cycle working.

Now I have a dilemma and would greatly appreciate any opinions. I have two practically identical programs. One is a windows service (the final program), one is just a C# foms app..

I drop my 2000 files into lets say my spool folder in the forms app. It processes the lot without any exceptions, run time errors etc.... I do the same in the windows service which has a timer set to check the folder every 1 sec to see if anything is in it. Everything else is the same yet the timer seems to stop every now and then. So I stop/start the service and the process carrys on until the next interupt.

The try, finally resolves this problem. Though it feels like I'm essentially kicking the can down the road. There is still an underlying problem somewhere causing the timer to stop.
However, as previously mentioned the code and classes run fine in the forms app. So unlikely to be the code directly. Although the try, finally resolving the issues seems to insinuate there is a problem within the try which is forcing the timer to stop.

This is a real headache. From the information I have given you would you say that the problem is with my code or something external?
0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
eguilhermeConnect With a Mentor Commented:
One of the issues you might have, is that the service tries to read the file the same time whatever other program is writing it, therefore generates and file in use error, hence why the try/catch works, when the file is in use you dont crash the service.

What you can do, is encapsulate the try catch only for the section the error might occur, and if it does for a specific file, you skip it and go to the next one,

eg.
foreach (FileInfo f in allFiles)
{
      try
      {
            string filePath = Convert.ToString(myDirInfo + f.ToString());                        
            FileReader myFileReader = new FileReader ();
            myFileReader .SetFilePath = filePath;
            myFileReader .ReadFile();
            File.Delete(filePath);
      }
      catch(Exception)
      {
            //may want to add loggin or something here
            continue;
      }
}

Open in new window

0
 
kbussAuthor Commented:
Cheers.
0
 
lenordisteCommented:
Also, I was thinking you might be interested in FileSystemWatcher:
http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx

This would allow you to receive events whenever a file is added to a directory for instance so no need to poll at regular intervals with a Timer. Just a suggestion but it might be a better way to handle your code :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.