简体   繁体   English

Thread.Sleep-如何以正确的方式使用它?

[英]Thread.Sleep - how to use it in a proper way?

System.Threading.thread.Sleep(1000); pauses a whole program for 1 second, but when this second is over it does everything what could be done for this period. 暂停整个程序1秒钟,但是当此秒结束时,它会执行这段时间内可以执行的所有操作。 For example: 例如:

Thread.Sleep(1000);
Console.WriteLine("A");
Thread.Sleep(1000);
Console.Writeline("B");

It will wait two seconds and write 它将等待两秒钟并写入

A 一种
B

How to use the pause properly? 如何正确使用暂停?

If you want something to happen once per second, then create a timer. 如果您希望每秒发生某件事,请创建一个计时器。 For example: 例如:

private System.Threading.Timer _timer;

void main()
{
    _timer = new Timer(TimerTick, null, 1000, 1000);
    // do other stuff in your main thread
}

void TimerTick(object state)
{
    // do stuff here
}

There are several different types of timers. 有几种不同类型的计时器。 If you're writing a console program, then I would suggest using System.Threading.Timer . 如果您正在编写控制台程序,则建议使用System.Threading.Timer In a Windows Forms application, either System.Windows.Forms.Timer or System.Timers.Timer . 在Windows Forms应用程序中,可以使用System.Windows.Forms.TimerSystem.Timers.Timer See Timers for more information. 有关更多信息,请参见计时器

Thread.Sleep() behaves just like you would think; Thread.Sleep()行为与您想象的一样; it just pauses the current thread for approximately the given number of milliseconds. 它只是将当前线程暂停大约给定的毫秒数。

The problem here is that the standard output stream does not necessarily flush to the console (or wherever it is pointed at) to on each call to Write. 这里的问题是在每次调用Write时,标准输出流不一定刷新到控制台(或指向它的任何地方)。 Instead, it may buffer some content so as to write it out in larger chunks for efficiency. 取而代之的是,它可以缓冲某些内容,以便将其更大的部分写出来以提高效率。 Try calling Console.Out.Flush() ; 尝试调用Console.Out.Flush() ; after each WriteLine() and you should see the results you expect. 在每个WriteLine()之后,您应该看到期望的结果。

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

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