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?
In this specific scenario, the
Taskreturned fromExecuteAsyncis 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.