sleep-until 在 c# 中

问题描述 投票:0回答:4

我想每1秒定期运行一个函数,所以10秒后它会执行10次。 最简单的方法是使用这样的循环:

while(true)
{
Thread.Sleep(1000);
function();
}

但这种方法的主要问题是它不会提供任何定期保证。 我的意思是,如果运行 function() 需要 0.1 秒,则该函数的执行时间将如下所示: 0, 1.1, 2.2, 3.3, 4.4, ...

我记得,在实时语言 ADA 中,我们有一个函数 sleep-until(#time)。现在我正在寻找 C# 的替代方案。

任何示例代码都将被赞赏。

c# thread-sleep
4个回答
7
投票
System.Threading.Timer timer = new System.Threading.Timer(ThreadFunc, null, 0, 1000);

private static void ThreadFunc(object state)
{
    //Do work in here.
}

请参阅 MSDN 了解更多信息。


3
投票

您可以使用

Stopwatch
来测量时间。我也会用
For-Loop
代替。

var sw = new System.Diagnostics.Stopwatch();
var timeForOne = TimeSpan.FromSeconds(1);
var count = 10;
for(int i = 0; i < count; i++)
{
    sw.Restart();
    function();
    sw.Stop();
    int rest = (timeForOne - sw.Elapsed).Milliseconds;
    if (rest > 0)
        System.Threading.Thread.Sleep(rest);
}

1
投票

要在特定时间间隔后调用某些内容,您应该使用 Timer 类。 这是教程


0
投票

最近也需要这个功能,并找到了一个解决方案来实现它,而无需处理计时器回调。精度与计时器相同 - 不会失控,可以根据系统时钟分辨率等待更长的时间。

// Thread can be declared globally and reused
var thread = new Thread(() => Thread.Sleep(Timeout.Infinite));
thread.Start();

var startTime = DateTime.UtcNow;
Console.WriteLine($"Start time: {startTime:HH:mm:ss.fff}");
for (var i = 0; i < 100; ++i)
{
    var waitTime = (startTime + TimeSpan.FromSeconds(i * 1)) - DateTime.UtcNow;
    if (waitTime <= TimeSpan.Zero)
    {
        continue;
    }
    thread.Join(waitTime);
    Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss.fff}    {i}");
}
© www.soinside.com 2019 - 2024. All rights reserved.