title: lock with while loop on multthread application form c# blocking all threads on single core machine
body: <p>I am having a problem with my multi-threaded app on windows form C# application. This application works fine on multicore machine, but then when it runs in a single core machine all the threads hang. I'm using <code>backgroundWorker</code>, code follow as this:</p>
  
  <pre><code> class custonTime // delay class
   {
       public void sleep_sec(int sleep)
       {
           int time_now = Environment.TickCount;
           int time_sleep = sleep;
           while ((Environment.TickCount - time_now) &lt; time_sleep) ;
       }
   }
  </code></pre>
  
  <p>When I press a button on UI the flags <code>action</code> and <code>doAlways</code> are set to <code>true</code> and the following backgroundworkers are started. The backgorundworker1 await and fire the task on right time the other one does the task:</p>
  
  <pre><code> private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
   {
       while(action)
       {
           if(doItAlways)
           {
               //do important tasks
           }
           if(task1)
           { 
               //do things
               task1 = false;
           }
           if(task2)
           { 
               //do things
               task1 = false;
           }
      }
  }
  
  private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  {
      task1=true;
      manegerTimewr2.sleep_sec(12000);//call delay class to wait 12 secs
      task2=true;
      manegerTimewr2.sleep_sec(12000);//call delay class to wait 12 secs
  }
  </code></pre>
  
  <p>My delay class lock not just my <code>backgorundworker1</code> but the <code>backgroundworker2</code> as well, make impossible to do the tasks fired by flag <code>doItAlways</code>, the application is only released when the while loop finish.</p>
  
  <p>And it just happens on single core machine only.</p>
  
  <p>Is there another method? A direct and easy method to hang a thread until elapse some time without block the other ones? </p>
  
  <p><strong>Note <code>Thread.Sleep</code> won't work because the time elapsed varies too much on different machines.</strong></p>