Thread.Sleep(1) 在 C# 中有什么影响? [英] What is the impact of Thread.Sleep(1) in C#?

查看:42
本文介绍了Thread.Sleep(1) 在 C# 中有什么影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 windows 窗体应用程序中调用 Thread.Sleep(1) 有什么影响,如下面的代码所示:

In a windows form application what is the impact of calling Thread.Sleep(1) as illustrated in the following code:

public Constructor()
{
    Thread thread = new Thread(Task);
    thread.IsBackground = true;
    thread.Start();
}

private void Task()
{
    while (true)
    {
        // do something
        Thread.Sleep(1);
    }
}

这个线程会占用所有可用的 CPU 吗?

Will this thread hog all of the available CPU?

我可以使用哪些分析技术来衡量此线程的 CPU 使用率(任务管理器除外)?

What profiling techniques can I use to measure this Thread's CPU usage ( other than task manager )?

推荐答案

如前所述,您的循环不会占用 CPU.

As stated, your loop will not hog the CPU.

但要注意:Windows 不是实时操作系统,因此您不会从 Thread.Sleep(1).如果您尚未使用 timeBeginPeriod 来设置您的最低分辨率,您将大约每 15 毫秒唤醒一次.即使您将最小分辨率设置为 1 毫秒,您仍然只能每 3-4 毫秒唤醒一次.

But beware: Windows is not a real-time OS, so you will not get 1000 wakes per second from Thread.Sleep(1). If you haven't used timeBeginPeriod to set your minimum resolution you'll wake about every 15 ms. Even after you've set the minimum resolution to 1 ms, you'll still only wake up every 3-4 ms.

为了获得毫秒级计时器粒度,您必须使用 Win32 多媒体计时器 (C#包装器).

In order to get millisecond level timer granularity you have to use the Win32 multimedia timer (C# wrapper).

这篇关于Thread.Sleep(1) 在 C# 中有什么影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆