Solved

C# Windows Service Timer stopping

Posted on 2013-05-16
6
973 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
  • 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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
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

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

747 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now