Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8178497
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T23:46:52+00:00 2026-06-06T23:46:52+00:00

I have a requirement in my project (C#, VS2010, .NET 4.0) that a particular

  • 0

I have a requirement in my project (C#, VS2010, .NET 4.0) that a particular for 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 i = 0 to about 500,000 to 700,000 so the total loop time varies.

I have read following questions which are similar but they didn’t help in my case:

  1. What is the best way to exit out of a loop after an elapsed time of 30ms in C++
  2. How to execute the loop for specific time

So far I have tried using a Stopwatch object to track the elapsed time but it’s not working for me. Here are 2 different methods I have tried so far:

Method 1. Comparing the elapsed time within for loop:

Stopwatch sw = new Stopwatch();
sw.Start();

for (i = 0; i < nEntries; i++) // nEntries is typically more than 500,000
{
      // Do some stuff
      ...
      ...
      ...

      if (sw.Elapsed > TimeSpan.FromMilliseconds(200))
          break;
}

sw.Stop();

This doesn’t work because if (sw.Elapsed > TimeSpan.FromMilliseconds(200)) takes more than 200 milliseconds to complete. Hence useless in my case. I am not sure whether TimeSpan.FromMilliseconds() generally takes this long or it’s just in my case for some reason.

Method 2. Creating a separate thread to compare time:

Stopwatch sw = new Stopwatch();
sw.Start();                    
bool bDoExit = false;
int msLimit = 200;

System.Threading.ThreadPool.QueueUserWorkItem((x) =>
{
     while (bDoExit == false)
     {
        if (sw.Elapsed.Milliseconds > msLimit)
        {
            bDoExit = true;
            sw.Stop();
         }

         System.Threading.Thread.Sleep(10);
      }

});

for (i = 0; i < nEntries; i++) // nEntries is typically more than 500,000
{
      // Do some stuff
      ...
      ...
      ...

      if (bDoExit == true)
          break;
}

sw.Stop();

I have some other code in the for loop that prints some statistics. It tells me that in case of Method 2, the for loop definitely breaks before completing all the iterations but the loop timing is still 280-300 milliseconds.

Any suggestions to break a for loop strictly with-in 200 milliseconds or less?
Thanks.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T23:46:54+00:00Added an answer on June 6, 2026 at 11:46 pm

    For a faster comparison try comparing

    if(sw.ElapsedMilliseconds > 200)
       break;
    

    You should do that check in the beggining of your loop and also during the processing, (“// Do some stuff” part of the code) because it is possible, for example, that processing starts at 190 (beginning of the loop), lasts 20 and ends at 210.

    You could also measure average execution time of your processing (this is approximate because it relies on average time), this way loop should last 200 milliseconds or less, here is a demo that you can put in a Main method of a Console application and easily modify it for your application:

            Stopwatch sw = new Stopwatch();
            sw.Start();
    
            string a = String.Empty;
            int i;
            decimal sum = 0, avg = 0, beginning = 0, end = 0;
            for (i = 0; i < 700000; i++) // nEntries is typically more than 500,000
            {
                beginning = sw.ElapsedMilliseconds;
                if (sw.ElapsedMilliseconds + avg > 200)
                    break;
    
                // Some processing
                a += "x";
                int s = a.Length * 100;
                Thread.Sleep(19);
                /////////////
    
                end = sw.ElapsedMilliseconds;
                sum += end - beginning;
                avg = sum / (i + 1);
    
            }
            sw.Stop();
    
            Console.WriteLine(
              "avg:{0}, count:{1}, milliseconds elapsed:{2}", avg, i + 1,
              sw.ElapsedMilliseconds);
            Console.ReadKey();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In our project we have requirement that, after receiving sms message from third party
In our project we have a requirement that when a set of records are
For a project we have a requirement to create an interfacedefinition that will return
On the project that I'm currently working I have a requirement to run a
I am using ASP.NET and C# in my project. I have a requirement where
I have a requirement in my .NET project where I need to select an
I have a project requirement that we need to attach an HTML formatted log
I have a requirement for a project that is hosted in a shared hosting
I'm using ASP.NET MVC in a project and I have a requirement like this..
I currently have a web application project that also includes web services within the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.