简体   繁体   中英

Multiple threads with infinite loop and thread.sleep high CPU usage

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.

A thread that is sleeping with Thread.Sleep() consumes zero CPU resources, so trying to improve on this using EventWaitHandle primitives or other means is pointless. You can't beat zero. What you could improve is the RAM consumed by the threads, which is 1 MB for their stack, plus the memory they allocate on the heap (which depends on what they do while working). So by using a single thread instead of three you could reduce the RAM consumption by 2 MB or more, which for a console app running on a modern PC is practically nothing. So I wouldn't be concerned about it in your place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM