C10
C10

Reputation: 71

Asynchronous operation suddenly stops?

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

Upvotes: 1

Views: 189

Answers (1)

pakeha_by
pakeha_by

Reputation: 2244

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

Upvotes: 0

Related Questions