Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

What is the most efficient way to query a database at a set interval in a Windows service? I am not concerned about database performance, only the performance in keeping the interval.

 

Thanks

Posted

Create an endless loop, then use Thread.Sleep(miliseconds) to pause the service for a specified time. This is not completly accurate because the processing time of your code will be added to the sleep time.

 

You could also create a timer System.Timers.Timer and have this raise an event which calls your code , then you set off a new thread and reset the timer for the next interval. This should be more accurate.

Posted

Don't use Sleep

 

If you use Sleep( ms ) to do your timing, you are going to be unhappy. The whole time your program is sleeping, it isn't responding to windows messages. I wrote a program that downloads a file at 6:30 or so every morning. I couldn't get it to respond (showed up as not responding in task manager) while I was using System.Threading.Thread.Sleep(). So, I looked around on MSDN, and found system timers. The idea is, you create a timer of a specific duration. Once your program starts, you initialize the timer. Then, every <time interval> later, you receive a WM_TIMER message. Then you can use that message to call your database connection. This way, your program still responds to other messages while waiting for the correct time.

 

BTW, in my application, every time I got a WM_TIMER message, I checked to see if the time was within my startup window, and then processed. If not, I just wait for the next WM_TIMER message, and check again.

 

To add the timer to your code, go to design view, and click on the system tab on the left. Drag the timer icon to your program, then you can set its properties. Then just handle timer1.elapsed() events.

  • *Gurus*
Posted
The alternative is to do as you're doing now and use Sleep, but only sleep for half a second or so at a time, in a loop. This will use up only a negligible amount of CPU but your process will still respond in a timely manner.

MVP, Visual Developer - .NET

 

Now you see why evil will always triumph - because good is dumb.

 

My free .NET Windows Forms Controls and Articles

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...