Notifications
Sign Up Sign In
Q&A

Which abstraction should I choose for background services and why?

+4
−0

Which concept is best for managed background services?

1. RunAsync(CancellationToken):

interface IWorker
{
    Task RunAsync(CancellationToken cancellationToken = default);
}

...

IWorker worker = ...;
var source = new CancellationTokenSource();
_ = worker.RunAsync(source.Token);

// And when it's time to shutdown the worker:
source.Cancel();

vs

2. RunAsync and StopAsync

interface IWorker
{
    Task RunAsync();
    Task StopAsync();
}

...

IWorker worker = ...;
_ = worker.RunAsync();

// And when it's time to shutdown the worker:
await worker.StopAsync();
Why should this post be closed?

2 comments

"Best" in what way? ‭Derek Elkins‭ 8 days ago

It's probably worth noting that these don't provide equivalent interfaces. In particular, the CancellationToken approach does not provide you with a way of telling when the cancellation is "complete". The second interface would be closer to the former if StopAsync returned void (at which point Stop would be a better name). If you need this functionality, then the first interface isn't an option, at least not naively used. ‭Derek Elkins‭ 8 days ago

0 answers

Sign up to answer this question »