Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Task.Run vs BackgroundService in ASP.NET

Tags:

c#

asp.net

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?

like image 475
Tono Nam Avatar asked Oct 24 '25 16:10

Tono Nam


2 Answers

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:

  1. It gets notified when the application starts or stops.

  2. It handles exceptions like OperationCanceledException.

like image 176
shingo Avatar answered Oct 26 '25 04:10

shingo


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 capabilities
  • Task is always available, straightforward and simple - but you solve everything yourself

Tip: look for your piece of code

_ = Task.Run(async () => ...

are you sure that that discard _ is ok?

like image 39
PavelP Avatar answered Oct 26 '25 04:10

PavelP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!