Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overlooping in C#

Tags:

c#

loops

sleep

I am going to create a system service in C#.

In the onstart section I would like to loop every 30 seconds and query a mysql database. If numrows are greater than 0 I will process some faxes using the faxcom library.

My question is: Would looping every 30 seconds exhaust the program/computer? What would be the best function/method to use for the loop and sleep? Do you have any example code for the loop and sleep?

like image 543
Jake H. Avatar asked Jun 16 '26 14:06

Jake H.


2 Answers

Using Thread.Sleep() would be a bad solution, because even while sleeping your thread is active. Use Timer class instead and handle its Elapsed event.

This article examines different ways to tackle the periodical execution of your service.

Here is what your OnStart method might look like:

using System.Timers; 

private timer = new Timer();

protected override void OnStart(string[] args)
{
 timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
 timer.Interval = 30000; // every 30 seconds
 timer.Enabled = true;
}

Private void OnElapsedTime(object source, ElapsedEventArgs e)
{
   // Execute your code here
}
like image 89
Alexander Galkin Avatar answered Jun 18 '26 03:06

Alexander Galkin


I wouldn't use looping constructs for such a thing.

I would use one of the timer controls in the BCL and set it to fire every 30 seconds.

As for the question of if this is "too much", the answer entirely depends on the amount of work being done and the load it generates.

like image 32
Oded Avatar answered Jun 18 '26 04:06

Oded