I have this simple minimal API:
var builder = WebApplication.CreateBuilder(args);
// my long running process <----
builder.Services.AddHostedService<MyBackgroundService>();
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
And here is MyBackgroundService:
public class MyBackgroundService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while(stoppingToken.IsCancellationRequested == false)
{
await Task.Delay(1000); // wait 1 second
Console.WriteLine("doing work..."); // do work
}
}
}
And here is the same program written using a Task instead of using a background service:
var builder = WebApplication.CreateBuilder(args);
// my long running process in a task instead of a background service
_ = Task.Run(async () =>
{
while (true) {
await Task.Delay(1000); // wait 1 second
Console.WriteLine("doing work..."); // do work
}
});
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
Why do tutorials and places on the internet encourage you to use BackgroundService? Will it be wrong practice if I use the second approach where I use Task.Run? What will be the difference of using the first approach vs using the second approach?
After review the source code of the Host class, I am pretty sure that a BackgroundService is a normal task except for the following features:
It gets notified when the application starts or stops.
It handles exceptions like OperationCanceledException.
It's up to you.
Basically, it's a question of whether to use the existing framework or do it your own way.
If it's a mini project for up to 3 people and you're not planning to deploy to Azure, I wouldn't be afraid to use a your own solution - Task.
Otherwise, I would reach for BackgroundService.
Nicely described here: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-6.0&tabs=visual-studio
BackgroundService allows integration into a larger ecosystem with rich monitoring capabilitiesTask is always available, straightforward and simple - but you solve everything yourselfTip: look for your piece of code
_ = Task.Run(async () => ...
are you sure that that discard _ is ok?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With