Atif
Atif

Reputation: 159

Running a loop for specific time using timer in windows form application C#

I'm trying to make some calculations repeatedly for a specific amount of time (the time is variable and provided by the user.)

I tried using timer available in windows form application toolbox in visual studio, but there seems to be a problem. The program gets stuck when I start the timer and associate the variable for time with the while loop; the time variable is being decremented in each tick event of timer and I need to run the while loop as long as time is greater than 0.

private void timer1_Tick(object sender, EventArgs e)
    {
        if (time == 0)
            timer1.Stop();

        else
        {
            time--;
            textBoxTime.Text = time.ToString();
        }

    }

and here is the while loop that blocks the program

while (time>0)
{
   computations();
}

Upvotes: 0

Views: 2881

Answers (3)

Peyman
Peyman

Reputation: 3138

You can use Stopwatch

Also it's better put sleep in loop to avoid takes all your machine resource

 var sw = new Stopwatch();
 sw.Start();
 while(sw.Elapsed.TotalSeconds < 100 /*Time in second*/)
 {
    /// TODO
    Thread.Sleep(100 /*Time in millisecond*/);
 }
 sw.Stop();

Upvotes: 0

JasonWilczak
JasonWilczak

Reputation: 2403

You can use the Timer class for this a simple sample is this:

Clock=new Timer();
Clock.Interval=time;
Clock.Start();
Clock.Tick+=new EventHandler(OnTimer_Tick);

Where OnTimer_Tick is a function that does some work

public void OnTimer_Tick(object sender,EventArgs eArgs)
{
//do computations here
}

Here is a related SO post

Edit: Your while loop is running faster than a tick so you are running a lot of loops. I updated timer to use the time variable as it's interval value and get rid of the while loop and do the computations on each tick.

Upvotes: 0

Eric J.
Eric J.

Reputation: 150108

i'm trying to make some calculations repeatedly for a specific amount of time the time is variable and provided by the user.

Rather than use a timer to count down the time for you in ticks, I would suggest you have the loop itself note when it started, check the current time at each loop iteration, and see if it has been running long enough.

and here is the while loop that blocks the program

Presumably you are performing the calculation on your UI thread. This will prevent any UI messages from being processed, including the timer ticks, thus making the application unresponsive.

Start a separate thread to perform the actual calculation. BackgroundWorker is a common means to do this from WinForms, though there are many approaches.

Upvotes: 5

Related Questions