gpt4 book ai didi

c# - 如何每 N 分钟重置一个递增计数器

转载 作者:太空宇宙 更新时间:2023-11-03 20:52:17 24 4
gpt4 key购买 nike

我的程序中有一个计数器,我想每 10 分钟将其重置为 0。

我的程序预计会引发事件。这些事件对应于由于大量使用资源或超出我们实验中的测试场景而发出的警告,这将需要采取一些措施,例如以 CSV 格式转储一些与测试相关的数据和以 Tiff 格式转储一些图。当事件计数器达到 3 时,将每 1 分钟生成一次 Tiff 文件。

但由于 Tiff 文件很大,我不希望过度生成这些文件。因此,重置计数器将确保只有重复发生的事件才会被跟踪以采取进一步行动。

在不添加太多不必要的细节的情况下,我的程序的主要结构如下:

class Program
{
static void Main(string[] args)
{
counter = 0;

using (an API)
{
// do something here, which may raise an event

while (event)
{
// take an action

counter++; // keeps track of events raised
}

if (counter > 3)
{
// take a specific action
}
else
{
// take action B
}

counter = 0; // reset counter every 10 minutes, by calling a timer or async method

// to keep the application going
System.Windows.Forms.Application.Run();
}
}

// a timer method() // to help me reset the counter
// or
// an Async method ResetCounter()
}

我试图通过创建一个定时器方法来启动一个定时器:

private static bool TimeCounter() 
{
System.Timers.Timer _delayTimer = new System.Timers.Timer();
_delayTimer.Interval = 100000;
_delayTimer.Enabled = true;
// _delayTimer.Elapsed += new ElapsedEventHandler(_delayTimer_Elapsed); // attempted to use an additional method as well that could get triggered after 10 mins but it gets too complicated
_delayTimer.Start();
// not sure how to set this timer to return a boolean true when time elapsed, rather than calling another method
_delayTimer.AutoReset = autoreset;
}

private static void _delayTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
ResetCounter(); // the method not created yet
}

但是采用定时器方法,首先,我不确定如何让这个定时器在时间结束时返回一个 bool 值 true,其次,如果每次程序通过 if-else 条件时,我在 main 方法中的 API 都调用此方法,这可能会再次重置计时器,而不会让第一个 10 分钟计时器过去。

所以遇到 async-await 我觉得这对我来说可能是一个更好的选择,我可能会调用这样的东西(在 Stackoverflow 上看到)来重置计数器?:

var result = Task.Run(async () => { return await myAsyncMethod(); }).Result;

我之前从未使用过 async-await,所以不确定如何使用 async-await 实现预期的结果。

最佳答案

我会简单地使用 DateTime.Now

1) 每当您重置计时器或代码将首次执行时保存当前时间:

var lastReset = DateTime.Now;

2) 检查 lastReset 是否在 10 分钟或更早之前:

if(lastReset.AddMinutes(10) <= DateTime.Now)
{
counter = 0;
}

关于c# - 如何每 N 分钟重置一个递增计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54110379/

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