我如何让我的c#程序睡眠(暂停执行)50毫秒?
当前回答
两全其美:
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);
}
其他回答
可读性:
using System.Threading;
Thread.Sleep(TimeSpan.FromMilliseconds(50));
System.Threading.Thread.Sleep(50);
记住,在主GUI线程中这样做会阻碍GUI的更新(它会感觉“迟缓”)。
只要把;使它也适用于VB.net。
使用这段代码
using System.Threading;
// ...
Thread.Sleep(50);
Thread.Sleep(50);
在指定的时间内,操作系统不会调度线程执行。该方法将线程的状态更改为包含WaitSleepJoin。
此方法不执行标准的COM和SendMessage抽取。 如果您需要在具有STAThreadAttribute的线程上休眠,但又希望执行标准COM和SendMessage泵送,请考虑使用指定超时间隔的Join方法的一个重载。
Thread.Join
在Windows中无法指定确切的睡眠时间。你需要一个实时的操作系统。最好的方法是指定一个最小睡眠时间。然后由调度器在此之后唤醒线程。永远不要在GUI线程上调用. sleep()。
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和