如何让我的 C# 程序休眠 50 毫秒?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/91108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get my C# program to sleep for 50 msec?
提问by TK.
How do I get my C# program to sleep for 50 milliseconds?
如何让我的 C# 程序休眠 50 毫秒?
This might seem an easy question, but I'm having a temporary brain failure moment!
这似乎是一个简单的问题,但我有一个暂时的脑力衰竭时刻!
采纳答案by Isak Savo
System.Threading.Thread.Sleep(50);
Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish")
但请记住,在主 GUI 线程中执行此操作会阻止您的 GUI 更新(它会感觉“缓慢”)
Just remove the ;
to make it work for VB.net as well.
只需删除;
即可使其也适用于 VB.net。
回答by Roger Lipscombe
Thread.Sleep
回答by Alexander Prokofyev
Use this code
使用此代码
using System.Threading;
// ...
Thread.Sleep(50);
回答by SelvirK
Thread.Sleep(50);
The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.
在指定的时间内,操作系统不会安排线程执行。此方法更改线程的状态以包含 WaitSleepJoin。
This method does not perform standard COM and SendMessage pumping. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.
此方法不执行标准 COM 和 SendMessage 泵送。如果您需要在具有 STAThreadAttribute 的线程上休眠,但想要执行标准 COM 和 SendMessage 泵送,请考虑使用指定超时间隔的 Join 方法的重载之一。
Thread.Join
回答by Joel Coehoorn
You can't specify an exactsleep time in Windows. You need a real-time OS for that. The best you can do is specify a minimumsleep time. Then it's up to the scheduler to wake up your thread after that. And nevercall .Sleep()
on the GUI thread.
您无法在 Windows 中指定确切的睡眠时间。为此,您需要一个实时操作系统。您能做的最好的事情是指定最短睡眠时间。然后由调度程序在此之后唤醒您的线程。并且永远不要调用.Sleep()
GUI 线程。
回答by Marcel Toth
There are basically 3 choices for waiting in (almost) any programming language:
在(几乎)任何编程语言中等待基本上有 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
- Combinationof previous 2
- It usually combines processing efficiency of 1. and preciseness + ability to do something of 2.
- 松散的等待
- 在给定时间内执行线程块(= 不消耗处理能力)
- 阻塞/等待线程无法处理
- 没那么精确
- 紧等待(也称为紧循环)
- 处理器在整个等待间隔内都非常忙碌(实际上,它通常会消耗 100% 的内核处理时间)
- 可以在等待时执行某些操作
- 非常精确
- 前2的
组合
- 它通常结合1.的处理效率和2的精确度+做某事的能力。
for 1. - Loose waiting in C#:
对于 1. - 在 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).
但是,windows 线程调度程序导致的精度Sleep()
约为 15 毫秒(因此睡眠可以轻松等待 20 毫秒,即使安排为仅等待 1 毫秒)。
for 2. - Tight waiting in C# is:
对于 2. - 在 C# 中的紧张等待是:
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).
我们也可以使用DateTime.Now
或 其他时间测量方法,但Stopwatch
速度要快得多(这在紧密循环中真的会变得可见)。
for 3. - Combination:
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
}
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).
此代码定期阻塞线程 1 毫秒(或稍长一些,取决于操作系统线程调度),因此处理器在阻塞期间并不忙,并且代码不会消耗 100% 的处理器功率。其他处理仍然可以在阻塞之间执行(例如:更新 UI、处理事件或进行交互/通信)。
回答by Toni Petrina
Since now you have async/await feature, the best way to sleep for 50ms is by using Task.Delay:
既然现在你有了 async/await 特性,那么休眠 50ms 的最好方法是使用 Task.Delay:
async void foo()
{
// something
await Task.Delay(50);
}
Or if you are targeting .NET 4 (with Async CTP 3 for VS2010 or Microsoft.Bcl.Async), you must use:
或者,如果您的目标是 .NET 4(使用 Async CTP 3 for VS2010 或 Microsoft.Bcl.Async),您必须使用:
async void foo()
{
// something
await TaskEx.Delay(50);
}
This way you won't block UI thread.
这样你就不会阻塞 UI 线程。
回答by Colonel Panic
For readability:
为了可读性:
using System.Threading;
Thread.Sleep(TimeSpan.FromMilliseconds(50));
回答by Akumaburn
Best of both worlds:
两全其美:
using System.Runtime.InteropServices;
[DllImport("winmm.dll", EntryPoint = "timeBeginPeriod", SetLastError = true)]
private static extern uint TimeBeginPeriod(uint uMilliseconds);
[DllImport("winmm.dll", EntryPoint = "timeEndPeriod", SetLastError = true)]
private static extern uint TimeEndPeriod(uint uMilliseconds);
/**
* Extremely accurate sleep is needed here to maintain performance so system resolution time is increased
*/
private void accurateSleep(int milliseconds)
{
//Increase timer resolution from 20 miliseconds to 1 milisecond
TimeBeginPeriod(1);
Stopwatch stopwatch = new Stopwatch();//Makes use of QueryPerformanceCounter WIN32 API
stopwatch.Start();
while (stopwatch.ElapsedMilliseconds < milliseconds)
{
//So we don't burn cpu cycles
if ((milliseconds - stopwatch.ElapsedMilliseconds) > 20)
{
Thread.Sleep(5);
}
else
{
Thread.Sleep(1);
}
}
stopwatch.Stop();
//Set it back to normal.
TimeEndPeriod(1);
}
回答by timmebee
Starting with .NET Framework 4.5, you can use:
从 .NET Framework 4.5 开始,您可以使用:
using System.Threading.Tasks;
Task.Delay(50).Wait(); // wait 50ms