title: Exit the loop after specific time in C#
body: <p>I have a requirement in my project (C#, VS2010, .NET 4.0) that a particular <code>for</code> loop must finish within 200 milliseconds. If it doesn't then it has to terminate after this duration without executing the remaining iterations. The loop generally goes for <code>i = 0</code> to about 500,000 to 700,000 so the total loop time varies.   </p>
  
  <p>I have read following questions which are similar but they didn't help in my case: </p>
  
  <ol>
  <li><a href="https://stackoverflow.com/questions/946167/what-is-the-best-way-to-exit-out-of-a-loop-after-an-elapsed-time-of-30ms-in-c">What is the best way to exit out of a loop after an elapsed time of 30ms in C++</a></li>
  <li><a href="https://stackoverflow.com/questions/5945533/how-to-execute-the-loop-for-specific-time">How to execute the loop for specific time</a></li>
  </ol>
  
  <p>So far I have tried using a <code>Stopwatch</code> object to track the elapsed time but it's not working for me. Here are 2 different methods I have tried so far: </p>
  
  <p><strong>Method 1.</strong> Comparing the elapsed time within <code>for</code> loop:</p>
  
  <pre><code>Stopwatch sw = new Stopwatch();
  sw.Start();
  
  for (i = 0; i &lt; nEntries; i++) // nEntries is typically more than 500,000
  {
        // Do some stuff
        ...
        ...
        ...
  
        if (sw.Elapsed &gt; TimeSpan.FromMilliseconds(200))
            break;
  }
  
  sw.Stop();
  </code></pre>
  
  <p>This doesn't work because <code>if (sw.Elapsed &gt; TimeSpan.FromMilliseconds(200))</code> takes more than 200 milliseconds to complete. Hence useless in my case. I am not sure whether  <code>TimeSpan.FromMilliseconds()</code> generally takes this long or it's just in my case for some reason. </p>
  
  <p><strong>Method 2.</strong> Creating a separate thread to compare time:</p>
  
  <pre><code>Stopwatch sw = new Stopwatch();
  sw.Start();                    
  bool bDoExit = false;
  int msLimit = 200;
  
  System.Threading.ThreadPool.QueueUserWorkItem((x) =&gt;
  {
       while (bDoExit == false)
       {
          if (sw.Elapsed.Milliseconds &gt; msLimit)
          {
              bDoExit = true;
              sw.Stop();
           }
  
           System.Threading.Thread.Sleep(10);
        }
  
  });
  
  for (i = 0; i &lt; nEntries; i++) // nEntries is typically more than 500,000
  {
        // Do some stuff
        ...
        ...
        ...
  
        if (bDoExit == true)
            break;
  }
  
  sw.Stop();
  </code></pre>
  
  <p>I have some other code in the for loop that prints some statistics. It tells me that in case of Method 2, the <code>for</code> loop definitely breaks before completing all the iterations but the loop timing is still 280-300 milliseconds. </p>
  
  <p>Any suggestions to break a for loop strictly with-in 200 milliseconds or less? 
  Thanks.</p>