I have a Windows service that has to execute a maximum of 10 threads in parallel, each of these threads reads information and saves it in the DB.
It could be the case that when reading the information from the device, it is down. This is why there has to be one thread per device so that a device that is turned off or has problems does not stop reading the rest.
In addition, each of the threads may or may not be working depending on a configuration that is in the database, that is, in the database it is saved for each device if it has to be read or not, and what information to retrieve from the device.
Every minute I have to read from the database the information regarding the configuration for each of the threads.
In OnStart
it I have defined the following:
cargaConfiguracion();
TimeSpan tsInterval = new TimeSpan(0, 0, periodoEjecucion, 0, 0);
IntervalTimer = new System.Threading.Timer(
new System.Threading.TimerCallback(callBack)
, null, tsInterval, tsInterval);
In configuration load I load the necessary information to know which devices and what information to load and then I call the method callback
that is the one that every "execution period = 1 minute" will read the configuration again.
What I need advice on is how and where it would be best to launch the multifloro process.
Right now I am doing tests and it is launching the following after the previous code:
for (int i = 0; i < 10; i++)
{
Task.Factory.StartNew(() => tareaPruebaHilos(i), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Current);
}
being the test function a function that only puts a log in the database
private static void tareaPruebaHilos(int hilo)
{
while (true)
{
Libreria.SQL_DAL.anadirLog("HILO Nº(" + hilo + ")");
}
}
In production the function tareaPruebaHilos
will have another name and it will check with the loaded configuration if it has to do something or not, and I am worried that when doing it with a while(true)
it will be infinitely doing nothing until the configuration tells it to read from its device again .
I don't know if it would be interesting in case you don't have to read anything from a certain device within the while(true)
add an thread.Sleep
or to stop it for a few seconds. I don't know what impact this would have with 10 threads.
The service will need to function for months or even years without being restarted.
I would appreciate it if you could tell me if this approach is robust and what problems can arise.
Thanks for the help.
The while(true) instruction does put a load on the processor which, indeed, as you mentioned, is quite alleviated with a waiting time (Thread.Sleep(1000);) no matter how small.
You can do the test yourself. Run code like this, and watch your processor load as you run it. At first glance you can see higher processor peaks in the first execution (without sleep) than in the second.
An interesting article that is more or less relevant: https://lapasiondepensar.wordpress.com/2018/09/28/ciclos-reloj/
Greetings.