简体   繁体   English

在C#.net中不使用Thread.Sleep的情况下在永不结束while循环中设置间隔?

[英]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. 每100毫秒间隔打印0到10次无限制时间。

I want this to be implemented in Windows Form. 我希望这可以在Windows窗体中实现。 But Thread.Sleep() actually paralyze the GUI. 但是Thread.Sleep()实际上使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. 您说要在Windows窗体中实现,但要使用控制台输出信息。 Ignoring that, you should add a System.Windows.Forms.Timer to the respective form, enable it and set it's tick interval to 100ms. 忽略这一点,您应该将System.Windows.Forms.Timer添加到相应的窗体,启用它并将其刻度间隔设置为100ms。

In the Tick event handler you should print your output to the form. 在Tick事件处理程序中,应将输出打印到表单。 The Tick event handler of the System.Windows.Forms.Timer runs in the UI thread so you have complete access to your form. System.Windows.Forms.Timer的Tick事件处理程序在UI线程中运行,因此您可以完全访问表单。

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. 要停止循环,请在if块中调用Timer.Stop

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. 但是,代码将无法与UI进行交互,因此您需要处理线程安全性。

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. 看看Reactive Extensions ,它是一个不错的计时器,您可以编写和过滤每x次迭代。

var timer = Observable.Timer(TimeSpan.FromMilliseconds(100));
timer.Subscribe(tick => Console.WriteLine((tick%10).ToString()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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