C# 频闪仪、Thread.Sleep

发布于 2024-10-11 05:08:05 字数 426 浏览 2 评论 0原文

我正在制作连接到计算机的简单频闪仪。 我有 Loop Like that:

double SleepTime = 1000 / Hz;

while ()
{
    BlinkAll();
    Thread.Sleep((int)SleepTime);
}

但这非常不准确。 如果赫兹 = 666 比 睡眠时间 = 1.5 和 (int)SleepTime = 1

这意味着输出时我得到 1000Hz 而不是 666Hz 这是很大的差异。

如何解决这个问题?

PS

这个例子仍然不太准确。它更好,但无论如何都不好:

double SleepTime = 1000 / Hz;
Thread.Sleep((int)SleepTime + 0.5)

I'm making simple stroboscope attached to computer.
I have Loop Like that:

double SleepTime = 1000 / Hz;

while ()
{
    BlinkAll();
    Thread.Sleep((int)SleepTime);
}

But this is very inaccurate.
If Hz = 666
than
SleepTime = 1.5
and
(int)SleepTime = 1

this means that on output I get 1000Hz not 666Hz This is big diffrence.

How to fix this?

P.S.

This example is still not to accurate. It's better but not good in any way:

double SleepTime = 1000 / Hz;
Thread.Sleep((int)SleepTime + 0.5)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

倚栏听风 2024-10-18 05:08:05

看一下 NtDelayExecution (ntdll.dll)...它似乎具有更好的粒度(单位为 100 纳秒而不是 1 毫秒),尽管我不确定这会有多大帮助,因为我认为 Windows 上的线程每个都需要几毫秒的时间片。

Take a look at NtDelayExecution (ntdll.dll)... it seems to have better granularity (units of 100-ns rather than 1 ms), although I'm not sure how much that will help because I think that threads on Windows take a few milliseconds of time slice each.

如何视而不见 2024-10-18 05:08:05

怎么样:

using System;
using System.Threading;
using System.Diagnostics;

static class Program
{
    static void Main()
    {
        const int Hz = 666;
        var t0 = DateTime.Now;
        int nCycles = 0;
        var sw = Stopwatch.StartNew();
        while (sw.ElapsedMilliseconds < 10000)
        {
            ++nCycles;
            var time = t0 + TimeSpan.FromMilliseconds(nCycles * 1000 / Hz);
            var ttw = (int)((time - DateTime.Now).TotalMilliseconds);
            if (ttw >= 1)
                Thread.Sleep(ttw);
        }
        Console.WriteLine(nCycles);
    }
}

How about something like:

using System;
using System.Threading;
using System.Diagnostics;

static class Program
{
    static void Main()
    {
        const int Hz = 666;
        var t0 = DateTime.Now;
        int nCycles = 0;
        var sw = Stopwatch.StartNew();
        while (sw.ElapsedMilliseconds < 10000)
        {
            ++nCycles;
            var time = t0 + TimeSpan.FromMilliseconds(nCycles * 1000 / Hz);
            var ttw = (int)((time - DateTime.Now).TotalMilliseconds);
            if (ttw >= 1)
                Thread.Sleep(ttw);
        }
        Console.WriteLine(nCycles);
    }
}
濫情▎り 2024-10-18 05:08:05

您尝试过 System.Timers.Timer 吗?
我相信它更准确并且接受毫秒,所以你可以非常准确

have you tried with System.Timers.Timer?
I believe it's much more accurate and accept milliseconds so you can be quite accurate

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文