windows service loop consumes more CPU time.

  • Thread starter Thread starter Ibrahim.
  • Start date Start date
I

Ibrahim.

Hello,

Im creating windows service program for the following purpose :

1. to save a file to the shared resource every 5 minutes. the file contents
come from the database.

2. i need to put the above task in the queue and execute the save task one
by one

what kind of threading model i need to use and the program design?

I will have a main thread, a worker thread (attached to a delegate). the
delegate function will have the following structure.


while (workerThreadStarted)
{
callSaveFile()
}
 
How do you make it do the saving every 5 min?

It seems it does it continuously in a while(){...) loop. That is why it
consumes CPU all the time.

You could use a System.Timers.Timer and have it tick every a few minutes and
handle the timer event. That is, do the savings in timer event handler (of
couse you want to make sure the saving could be done in the timer event
interval, or you do saving in a thread from a pool of threads...if the
saving takes time to finish).
 
Hello,

No, im not using a timer. the saving is done in ThreadPool.

yes im calling save method in while(){...) loop. That is why it
consumes CPU all the time.

Im connecting to Database in the loop & getting the file contents & then
pass to SaveMethod,

so it queries the Database for generating the file.

what do you suggest?

thanks,
 
Ibrahim. said:
Hello,

No, im not using a timer. the saving is done in ThreadPool.

yes im calling save method in while(){...) loop. That is why it
consumes CPU all the time.

Im connecting to Database in the loop & getting the file contents & then
pass to SaveMethod,

so it queries the Database for generating the file.

what do you suggest?

thanks,


So why are you not using the Thread.Sleep(milliseconds) on the thread
while in the loop?


So, on your start delegate for the thread would be like this.


While (true)
{

Method.Save();
Thread.Sleep(10000); // sleep 10 seconds

}

The only way the While will not be true is if you use a try/catch around the
While and there is an abort condition on the thread, most likely by your
Method.Save. You would shutdown the thread on the Onstop() event with a
Thread.Sleep(0) when stopping the service.

You should have a timer that firers an Elapsed event that always checks the
stare of the thread with If statement on the Thread.IsAlive.
 
Back
Top