我如何让我的c#程序睡眠(暂停执行)50毫秒?
当前回答
在(几乎)任何编程语言中,等待基本上有3种选择:
Loose waiting Executing thread blocks for given time (= does not consume processing power) No processing is possible on blocked/waiting thread Not so precise Tight waiting (also called tight loop) processor is VERY busy for the entire waiting interval (in fact, it usually consumes 100% of one core's processing time) Some actions can be performed while waiting Very precise Combination of previous 2 It usually combines processing efficiency of 1. and preciseness + ability to do something of 2.
为1。c#中的松散等待:
Thread.Sleep(numberOfMilliseconds);
然而,windows线程调度器导致Sleep()的准确性在15ms左右(所以Sleep可以很容易地等待20ms,即使计划只等待1ms)。
为2。c#中的紧等待是:
Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
//some other processing to do possible
if (stopwatch.ElapsedMilliseconds >= millisecondsToWait)
{
break;
}
}
我们也可以使用DateTime。现在或其他方式的时间测量,但秒表是快得多(这将真正成为在紧循环)。
为3。——组合:
Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
//some other processing to do STILL POSSIBLE
if (stopwatch.ElapsedMilliseconds >= millisecondsToWait)
{
break;
}
Thread.Sleep(1); //so processor can rest for a while
}
这段代码会定期阻塞线程1ms(或者稍微多一点,这取决于操作系统线程调度),所以处理器在阻塞期间并不繁忙,代码也不会消耗处理器100%的功耗。其他处理仍然可以在阻塞之间执行(例如:更新UI,处理事件或做交互/通信之类的事情)。
其他回答
既然现在你有了async/await特性,那么最好的睡眠50ms的方法就是使用Task。延迟:
async void foo()
{
// something
await Task.Delay(50);
}
或者如果你的目标是。net 4(使用VS2010的Async CTP 3或Microsoft.Bcl.Async),你必须使用:
async void foo()
{
// something
await TaskEx.Delay(50);
}
这样你就不会阻塞UI线程。
可读性:
using System.Threading;
Thread.Sleep(TimeSpan.FromMilliseconds(50));
System.Threading.Thread.Sleep(50);
记住,在主GUI线程中这样做会阻碍GUI的更新(它会感觉“迟缓”)。
只要把;使它也适用于VB.net。
在(几乎)任何编程语言中,等待基本上有3种选择:
Loose waiting Executing thread blocks for given time (= does not consume processing power) No processing is possible on blocked/waiting thread Not so precise Tight waiting (also called tight loop) processor is VERY busy for the entire waiting interval (in fact, it usually consumes 100% of one core's processing time) Some actions can be performed while waiting Very precise Combination of previous 2 It usually combines processing efficiency of 1. and preciseness + ability to do something of 2.
为1。c#中的松散等待:
Thread.Sleep(numberOfMilliseconds);
然而,windows线程调度器导致Sleep()的准确性在15ms左右(所以Sleep可以很容易地等待20ms,即使计划只等待1ms)。
为2。c#中的紧等待是:
Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
//some other processing to do possible
if (stopwatch.ElapsedMilliseconds >= millisecondsToWait)
{
break;
}
}
我们也可以使用DateTime。现在或其他方式的时间测量,但秒表是快得多(这将真正成为在紧循环)。
为3。——组合:
Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
//some other processing to do STILL POSSIBLE
if (stopwatch.ElapsedMilliseconds >= millisecondsToWait)
{
break;
}
Thread.Sleep(1); //so processor can rest for a while
}
这段代码会定期阻塞线程1ms(或者稍微多一点,这取决于操作系统线程调度),所以处理器在阻塞期间并不繁忙,代码也不会消耗处理器100%的功耗。其他处理仍然可以在阻塞之间执行(例如:更新UI,处理事件或做交互/通信之类的事情)。
使用这段代码
using System.Threading;
// ...
Thread.Sleep(50);