Asynchronous operation suddenly stops?

171 views Asked by At

So I have created this helper method to run a task every X ms, although the problem is the task suddenly stops executing after a few iterations and I can't understand why? No reason is given.

Helper method:

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

Usage:

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);
    }
}

And then in Program.cs:

var gameProcessor = _serviceProvider.GetRequiredService<IGameProcessor>();
gameProcessor.Boot(); // not awaited

// ... rest of my flow
1

There are 1 answers

1
pakeha_by On

Do not create new PeriodicTimer each cycle, use single instance instead:

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