简体   繁体   中英

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. 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 . In a Windows Forms application, either System.Windows.Forms.Timer or System.Timers.Timer . See Timers for more information.

Thread.Sleep() behaves just like you would think; 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. Instead, it may buffer some content so as to write it out in larger chunks for efficiency. Try calling Console.Out.Flush() ; after each WriteLine() and you should see the results you expect.

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