【发布时间】:2022-07-16 04:59:28
【问题描述】:
所以我创建了这个帮助方法来每 X 毫秒运行一个任务,尽管问题是任务在几次迭代后突然停止执行,我不明白为什么?没有给出任何理由。
辅助方法:
public static async Task RunPeriodically(TimeSpan timeSpan, Func<Task> task, CancellationToken cancellationToken)
{
while (await new PeriodicTimer(timeSpan).WaitForNextTickAsync(cancellationToken))
{
await task();
}
}
用法:
public class GameProcessor : IGameProcessor
{
private readonly CancellationTokenSource _cts;
public GameProcessor()
{
_cts = new CancellationTokenSource();
}
public async Task Boot()
{
await Task.Run(ProcessAsync);
}
public async Task ProcessAsync()
{
await TimerUtilities.RunPeriodically(TimeSpan.FromMilliseconds(500), _roomRepository.RunPeriodicCheckAsync, _cts.Token);
}
}
然后在 Program.cs 中:
var gameProcessor = _serviceProvider.GetRequiredService<IGameProcessor>();
gameProcessor.Boot(); // not awaited
// ... rest of my flow
【问题讨论】:
-
应用程序的类型是什么? ASP.NET? WinForms?
标签: c# .net asynchronous periodictimer