In my console application I have some threads and each thread have an infinite loop with a Thread.Sleep.
Have many threads because each one is independent from others.
Each cycle is run every waitingTime
time and I want that never stops.
static int waitingTime= 5 * 60 * 1000;
static void Main(string[] args)
{
Thread thread1 = new Thread(() => Thread1());
Thread thread2 = new Thread(() => Thread2());
Thread thread3 = new Thread(() => Thread3());
...
thread1.Start();
thread2.Start();
thread3.Start();
...
}
static void Thread1()
{
do
{
// Connect to DB and do something...
try
{
using (SqlConnection connection = MyDBClass.MyDBConnection())
{
connection.Open();
SqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT x, y FROM Table WITH (NOLOCK);";
SqlDataReader sdr = command.ExecuteReader();
while (sdr.Read())
{
MyObject obj = new MyObject(sdr[0] as string, ...);
MyStaticClass.SetMyObject(obj); // Open a new DB connection on different server and do an Update.
}
sdr.Close();
sdr.Dispose();
}
}
catch
{
}
Thread.Sleep(waitingTime);
}
while (true);
}
static void Thread2()
{
do
{
// Connect to DB and do something...
Thread.Sleep(waitingTime);
}
while (true);
}
...
I have read that is not good use Thread.Sleep() in cases like this and is suposes use solutions like EventWaitHandle. What is the best solution for this case and how to implement that.