【问题标题】:Asynchronous operation suddenly stops?异步操作突然停止?
【发布时间】: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


【解决方案1】:

不要在每个周期创建新的 PeriodicTimer,而是使用单个实例:

public static async Task RunPeriodically(TimeSpan timeSpan, Func<Task> task, CancellationToken cancellationToken)
{
    var timer = new PeriodicTimer(timeSpan);
    while (await timer.WaitForNextTickAsync(cancellationToken))
    {
        await task();
    }
}

【讨论】:

  • 嗨!感谢您的回答。我已经更新了我的代码以使用单个实例,但仍然收到它刚刚被丢弃的主要问题。
猜你喜欢
  • 1970-01-01
  • 2017-08-22
  • 2021-02-01
  • 2016-12-29
  • 2018-05-09
  • 2015-12-07
  • 2015-08-23
  • 2014-02-05
相关资源
最近更新 更多