Search code examples
.netasynchronousasync-awaitasp.net-core-hosted-services

Is it ok to return CompletedTask from BackgroundService.ExecuteAsync?


I have the following two alternatives:

protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
     _ = ForeverRunningLoop(stoppingToken);

     return Task.CompletedTask;
}

private Task ForeverRunningLoop(CancellationToken token)
{
     while(true)
     {
          token.ThrowIfCancellationRequested();
          // Do some asynchronous work...
     }
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
     await ForeverRunningLoop(stoppingToken);
}

private Task ForeverRunningLoop(CancellationToken token)
{
     while(true)
     {
          token.ThrowIfCancellationRequested();
          // Do some asynchronous work...
     }
}

Is there any difference between those? If so, which one is better?


Solution

  • In this specific scenario, the Task returned from ExecuteAsync is ignored, so there's no behavioral difference between the two.

    I would still recommend the second option (or just merge the methods completely as suggested in the comments), because it looks wrong to do a fire-and-forget discard like that. Code like the first option is a major red flag in literally any scenario other than ExecuteAsync.