Solved

C# Windows Service Timer stopping

Posted on 2013-05-16
6
1,057 Views
Last Modified: 2013-05-16
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.
0
Comment
Question by:kbuss
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 11

Accepted Solution

by:
lenordiste earned 300 total points
ID: 39170783
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
 

Author Comment

by:kbuss
ID: 39170827
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
 

Author Comment

by:kbuss
ID: 39171013
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
Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

 
LVL 10

Assisted Solution

by:eguilherme
eguilherme earned 200 total points
ID: 39171050
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
 

Author Comment

by:kbuss
ID: 39171123
Cheers.
0
 
LVL 11

Expert Comment

by:lenordiste
ID: 39172580
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

Featured Post

Stressed Out?

Watch some penguins on the livecam!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Introduction to Processes

630 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question