简体   繁体   中英

Set interval in never ending while loop without using Thread.Sleep in C#.net?

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.

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.

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.

Use this to make your interval loop

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

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()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM