让程序暂停的几种方法

refer to : http://stackoverflow.com/questions/91108/how-do-i-get-my-c-sharp-program-to-sleep-for-50-msec

here are basically 3 choices for waiting in (almost) any programming language:

  1. Loose waiting
    • Executing thread blocks for given time (= does not consume processing power)
    • No processing is possible on blocked/waiting thread
    • Not so precise
  2. 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
  3. Combination of previous 2
    • It usually combines processing efficiency of 1. and preciseness + ability to do something of 2.

for 1. - Loose waiting in C#:

Thread.Sleep(numberOfMilliseconds);

However, windows thread scheduler causes acccuracy of Sleep() to be around 15ms (so Sleep can easily wait for 20ms, even if scheduled to wait just for 1ms).

for 2. - Tight waiting in C# is:

Stopwatch stopwatch = Stopwatch.StartNew();
while (true)
{
    //some other processing to do possible
    if (stopwatch.ElapsedMilliseconds >= millisecondsToWait)
    {
        break;
    }
}

We could also use DateTime.Now or other means of time measurement, but Stopwatch is much faster (and this would really become visible in tight loop).

for 3. - Combination:

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
}

This code regularly blocks thread for 1ms (or slightly more, depending on OS thread scheduling), so processor is not busy for that time of blocking and code does not consume 100% of processor's power. Other processing can still be performed in-between blocking (such as: updating of UI, handling of events or doing interaction/communication stuff).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值