1
int i = 0;
while (i < 11)
{
    Console.WriteLine(i.ToString());
    i++;
    System.Threading.Thread.Sleep(100);
    if (i >10)
    {
        i = 0;
    }
}

You know what it does. It prints 0 to 10 unlimited times at every 100 milisecond interval.

I want this to be implemented in Windows Form. But Thread.Sleep() actually paralyze the GUI.

I've heard of timer but i haven't figured out good method to do this job using timer. Any help will be appreciated.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
HackTweaks
  • 41
  • 1
  • 2
  • 3

4 Answers4

2

You say you want to implement in Windows Forms but use Console to output the information. Ignoring that, you should add a System.Windows.Forms.Timer to the respective form, enable it and set it's tick interval to 100ms.

In the Tick event handler you should print your output to the form. The Tick event handler of the System.Windows.Forms.Timer runs in the UI thread so you have complete access to your form.

João Angelo
  • 56,552
  • 12
  • 145
  • 147
  • Take a look a the sample code in the [MSDN entry for the windows forms timer](http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx). – João Angelo Jan 12 '11 at 14:39
1

As you suspect, you need to use a timer.
You'll need to move the loop body into the timer callback.

To stop the loop, call Timer.Stop in an if block.

Alternatively, you could move your code to a background thread.
However, the code would not be able to interact with the UI, and you'll need to deal with thread safety.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

Use this to make your interval loop

while (1 > 0)
    {
          Console.WriteLine("do the job");
          System.Threading.Thread.Sleep(10000);//10 seconds
    }
Sinh Quan
  • 9
  • 1
0

Have a look into Reactive Extensions for a nice timer that you can compose and filter every x iterations.

var timer = Observable.Timer(TimeSpan.FromMilliseconds(100));
timer.Subscribe(tick => Console.WriteLine((tick%10).ToString()));
Mark H
  • 13,797
  • 4
  • 31
  • 45