How to execute the loop for specific time
Asked Answered
c#
I

7

33

How can i execute the a particluar loop for specified time

Timeinsecond = 600

int time = 0;
while (Timeinsecond > time)
{
   // do something here
}

How can i set the time varaible here, if i can use the Timer object start and stop method it doesnot return me time in seconds

Regards NewDev

Idolla answered 10/5, 2011 at 5:24 Comment(0)
P
79

May be the following will help:

  Stopwatch s = new Stopwatch();
  s.Start();
  while (s.Elapsed < TimeSpan.FromSeconds(600)) 
  {
      //
  }

  s.Stop();
Pertussis answered 10/5, 2011 at 5:27 Comment(0)
E
27

If you want ease of use:

If you don't have strong accuracy requirements (true millisecond level accuracy - such as writing a high frames per second video game, or similar real-time simulation), then you can simply use the System.DateTime structure:

// Could use DateTime.Now, but we don't care about time zones - just elapsed time
// Also, UtcNow has slightly better performance
var startTime = DateTime.UtcNow;

while(DateTime.UtcNow - startTime < TimeSpan.FromMinutes(10))
{
    // Execute your loop here...
}

Change TimeSpan.FromMinutes to be whatever period of time you require, seconds, minutes, etc.

In the case of calling something like a web service, displaying something to the user for a short amount of time, or checking files on disk, I'd use this exclusively.

If you want higher accuracy:

look to the Stopwatch class, and check the Elapsed member. It is slightly harder to use, because you have to start it, and it has some bugs which will cause it to sometimes go negative, but it is useful if you need true millisecond-level accuracy.

To use it:

var stopwatch = new Stopwatch();
stopwatch.Start();

while(stopwatch.Elapsed < TimeSpan.FromSeconds(5))
{
    // Execute your loop here...
}
Embroidery answered 10/5, 2011 at 5:25 Comment(2)
DateTime.Now is slow (about 1000ns on my machine). You should use DateTime.UtcNow instead because it's about 100 times faster due to not having to perform a timezone conversion.Wretch
@Gabe: Good information. Thanks for teaching me something :) Editing the answer...Embroidery
C
0

Create a function for starting, stopping, and elapsed time as follows:

Class CustomTimer
{ 
   private DateTime startTime;
    private DateTime stopTime;
    private bool running = false;

    public void Start() 
    {
        this.startTime = DateTime.Now;
        this.running = true;
    }

    public void Stop() 
    {
        this.stopTime = DateTime.Now;
        this.running = false;
    }

    //this will return time elapsed in seconds
    public double GetElapsedTimeSecs() 
    {
        TimeSpan interval;

        if (running) 
            interval = DateTime.Now - startTime;
        else
            interval = stopTime - startTime;

        return interval.TotalSeconds;
    }

}

Now within your foreach loop do the following:

    CustomTimer ct = new CustomTimer();
    ct.Start();
    // put your code here
    ct.Stop();   
  //timeinsecond variable will be set to time seconds for your execution.
  double timeinseconds=ct.GetElapsedTime();
Cowlick answered 10/5, 2011 at 5:41 Comment(0)
R
0

use Timers in c# http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx

Rhythmics answered 10/7, 2012 at 14:14 Comment(0)
L
0

It's ugly .... but you could try this:

DateTime currentTime = DateTime.Now;
DateTime future = currentTime.AddSeconds(5);
while (future > currentTime)
{
    // Do something here ....
    currentTime = DateTime.Now;
  // future = currentTime.AddSeconds(5);
}
Letterhead answered 23/3, 2015 at 23:43 Comment(0)
U
0
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Accord.Video.FFMPEG;


namespace TimerScratchPad
{
    public partial class Form1 : Form
    {
        VideoFileWriter writer = new VideoFileWriter();
        int second = 0;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            writer.VideoCodec = VideoCodec.H264;
            writer.Width = Screen.PrimaryScreen.Bounds.Width;
            writer.Height = Screen.PrimaryScreen.Bounds.Height;
            writer.BitRate = 1000000;
            writer.Open("D:/DemoVideo.mp4");

            RecordTimer.Interval = 40;
            RecordTimer.Start();

        }

        private void RecordTimer_Tick(object sender, EventArgs e)
        {
            Rectangle bounds = Screen.GetBounds(Point.Empty);
            using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
            {
                using (Graphics g = Graphics.FromImage(bitmap))
                {
                    g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
                }
                writer.WriteVideoFrame(bitmap);
            }

            textBox1.Text = RecordTimer.ToString();
            second ++;
            if(second > 1500)
            {
                RecordTimer.Stop();
                RecordTimer.Dispose();
                writer.Close();
                writer.Dispose();
            }
        }
    }
}
Urethra answered 4/2, 2018 at 6:24 Comment(1)
this code will run without consuming more system resources more and will never experience slowing system down like when you run while loop this code will take screen shots and write to video file for every 40 milliseconds i.e. 24FPSUrethra
B
-7

Instead of such an expensive operation I'd recommend this: It's nasty but it's better to sit than running for doing nothing heating the cpu unnecesarily, the question is may be academic.

using System.Threading;

Thread.Sleep(600000);
Byer answered 26/8, 2016 at 1:34 Comment(2)
Not a good idea to put the main thread to sleep. Waste of resources and NOT at all a good practice.Guttapercha
I toatally agree, however it's better to sit and wait than running wasting resources, the question itself is maybe academic.Byer

© 2022 - 2024 — McMap. All rights reserved.