Solved

C# Windows Service Timer stopping

Posted on 2013-05-16
6
1,029 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
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
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

MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

Question has a verified solution.

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

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
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.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …

737 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