Thursday, December 28, 2006

Coding with the correct Property

Be sure to use the right property when writing your code. I was looking back at one of my programs today trying to debug a process and found a bug.

My code
TimeSpan diff = DateTime.Now - System.IO.File.GetLastWriteTime(FileIn);
if( diff.Seconds < 3 )
{
Thread.Sleep(3000);
}

The quirk here is that if the file was last written 5 days, 4 hours 10 minutes and 1 second ago then this will wait 3 seconds before trying to process the file again.

I should instead have used TotalSeconds.
TimeSpan diff = DateTime.Now - System.IO.File.GetLastWriteTime(FileIn);
if( diff.TotalSeconds < 3 )
{
Thread.Sleep(3000);
}

This will return the total time in seconds. In my situation this wasn't a problem because it would only pause the process for 3 seconds and work correctly. If I had chosen to make the program wait 1 minute though, then everytime the timer fired it would have been less than 3 seconds. Also if I was checking minutes instead. I could have seriously slowed an automated process due simply to a failure to use the correct property.

No comments: