我如何让我的c#程序睡眠(暂停执行)50毫秒?
当前回答
System.Threading.Thread.Sleep(50);
记住,在主GUI线程中这样做会阻碍GUI的更新(它会感觉“迟缓”)。
只要把;使它也适用于VB.net。
其他回答
两全其美:
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);
}
System.Threading.Thread.Sleep(50);
记住,在主GUI线程中这样做会阻碍GUI的更新(它会感觉“迟缓”)。
只要把;使它也适用于VB.net。
使用这段代码
using System.Threading;
// ...
Thread.Sleep(50);
既然现在你有了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线程。
从.NET Framework 4.5开始,你可以使用:
using System.Threading.Tasks;
Task.Delay(50).Wait(); // wait 50ms
推荐文章
- 如何在c#中获得正确的时间戳
- Linq选择列表中存在的对象(A,B,C)
- c# .NET中的App.config是什么?如何使用它?
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 更好的方法将对象转换为int类型
- 我可以将c#字符串值转换为转义字符串文字吗?
- 在c#中转换char到int
- c#中朋友的对等物是什么?
- 关键字使用virtual+override vs. new
- 在ASP中选择Tag Helper。NET Core MVC
- 如何在没有任何错误或警告的情况下找到构建失败的原因
- 跨线程操作无效:控件“textBox1”从创建它的线程以外的线程访问
- 否ConcurrentList<T>在。net 4.0?
- 在c#中解析字符串为日期时间