Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Disable the timer while function is executing 1

Status
Not open for further replies.

EwS

Programmer
Dec 30, 2002
398
0
0
US
I have a Windows Service with the timer - every 15 seconds I'm calling a function. I need to add some logic to tell the timer to "wait" until the function is done executing its code (which can exceed 15 seconds) because I don't wait the timer to "hit" the function while it's still executing. What I'm planning to do is in my OnElapsedTime(), I'll stop the timer, execute my code and then start the timer again. Is this an efficient way of doing things? Or there's a better way to accomplish what I want?

Thank you for any responses.
 
I thought of another solution, which I think is a better approach. Rather than having a timer kick off the function, I would have a loop and inside the loop I would call the function, after the function finished executing, I sleep for 15 seconds. Here's some pseudocode:

while (1)
{
try
{
ProcessFiles();
System.Threading.Thread.Sleep(15000);
}
catch (Exception ex)
{
// stop the loop
}
}

I would think this would be more efficient...
 
Uhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh

Look at the BackgroudWorkerThread.

while(true) is not an option unless you like 100% CPU utilization

 
I looked at BackgroundWorker thread and it looks like that's what I'm going to use.
I realize while(true) is not good, but what else can I use if I need my service to execute some logic every 15 seconds? Do I really have any other choice?
 
Use a timer - and while you are doing work, set a boolean that says the system is working - wait until it's done.

0 seconds
15 seconds - ProcessFiles Started
30 seconds - ProcessFiles did not finish so we wait for the next tick event
35 seconds - ProcessFiles Finished
45 seconds - ProcessFiles Started
55 seconds - ProcessFiles Finished
60 seconds - ProcessFiles Started....

etc.


 
Having a flag that says the thread is currently executing is better than stoping the timer when the thread starts executing and starting the timer once it's done?
 
I guess the flag approach is not that heavy on resources.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top