gpt4 book ai didi

c# - 你会如何限制每秒的操作次数?

转载 作者:太空狗 更新时间:2023-10-29 19:53:18 24 4
gpt4 key购买 nike

如何限制每秒的操作数?

假设我们必须将文件从一个位置复制到另一个位置,并且我们不希望每秒处理超过 5 个文件。

请看我在做什么

private static string currentStamp;
private static int processedInCurrentStamp = 0;

private static void Main(string[] args)
{
currentStamp = DateTime.Now.ToString("{0:d/M/yyyy HH:mm:ss}");
Run();
}

private static void Run()
{
for (int i = 0; i < Int32.MaxValue; i++)
{
string s = DateTime.Now.ToString("{0:d/M/yyyy HH:mm:ss}");
if (currentStamp.Equals(s))
{
if (processedInCurrentStamp < 5)
{
ProcessItem();
processedInCurrentStamp++;
}
}
else
{
Console.WriteLine("{0} ::: {1}", currentStamp, processedInCurrentStamp);
currentStamp = s;
processedInCurrentStamp = 0;
}
}
}

但我需要一种更优雅、防弹的方法。

最佳答案

获取起始时间,然后在循环中计算到当前时间应该处理的最大文件数,领先就休眠:

DateTime start = DateTime.UtcNow;

int i = 1;
while (i <= 100) {

int limit = (int)((DateTime.UtcNow - start).TotalSeconds * 5.0);

if (i <= limit) {

Console.WriteLine(i);
i++;

} else {
Thread.Sleep(100);
}

}

如果某些操作需要更长的时间,代码将 catch 。如果你一秒钟只能进行 3 次操作,那么下一秒它可以进行 7 次操作。

请注意,我使用 UtcNow 而不是 Now 以避免每年发生两次令人讨厌的时间跳跃。

编辑:

另一种方法是测量操作所花费的时间,然后休眠剩余的时间段:

for (int i = 1; i <= 100; i++ ) {

DateTime start = DateTime.UtcNow;

Console.WriteLine(i);

int left = (int)(start.AddSeconds(1.0 / 5.0) - DateTime.UtcNow).TotalMilliseconds;
if (left > 0) {
Thread.Sleep(left);
}

}

关于c# - 你会如何限制每秒的操作次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4085055/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com