我在主程序中设置了一个定时器逻辑为每30秒AutorReset一次,因此我的LogCollection方法(提取数据)将每30秒循环一次,并且我的代码可以继续运行。
问题是,我意识到有时给定的时间比方法执行时间要短,这会导致同时调用多个方法,从而导致多个数据泛滥。
问:如何让计时器等待,并且在方法结束之前不执行另一个循环?
计时器代码如下所示:
Timer thetimer = new Timer(TimeSpan.FromSeconds(30).TotalMilliseconds);
thetimer.Elapsed += new System.Timers.ElapsedEventHandler(LogCollector.LogCollection);
thetimer.AutoReset = true;
thetimer.Start();我正在考虑添加一些While循环,但我的代码将永远循环在该循环上,而其余的代码将无法完成。请指教
发布于 2020-10-01 19:55:22
我会放弃Timer,转而使用async:
while (true)
{
var start = DateTime.Now;
LogCollector.LogCollection();
var timeRemaining = TimeSpan.FromSeconds(30) - (DateTime.Now - start);
await Task.Delay(Math.Max(timeRemaining.TotalMilliseconds, 0));
}如果LogCollection()的执行超过30秒,则使用Math.Max,在这种情况下,timeRemaining将为负。
如果要在循环之后运行代码,请将其移动到cancellable方法中:
async Task LogCollectionLoopAsync(TimeSpan minLoopTime, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
var start = DateTime.Now;
LogCollector.LogCollection();
var timeRemaining = minLoopTime - (DateTime.Now - start);
await Task.Delay(Math.Max(timeRemaining.TotalMilliseconds, 0), ct);
}
}那么你的Main方法可以写成这样:
async Task Main()
{
var cts = new CancellationTokenSource();
var logCollectionTask = LogCollectionLoopAsync(TimeSpan.FromSeconds(30), cts.Token);
// Do your other stuff
cts.Cancel();
try { await logCollectionTask; } catch { } // Cancellation causes an exception
}https://stackoverflow.com/questions/64153641
复制相似问题