DEV Community

Cover image for Understanding IHostedService and BackgroundService in .NET 🌍
Mo
Mo

Posted on

Understanding IHostedService and BackgroundService in .NET 🌍

Hello, lovely people! 👋 If you’re a .NET developer, you’ve likely come across the terms IHostedService and BackgroundService. But what exactly are these, and when should you use them? 🤔 Well, grab yourself a nice cuppa, and let’s dive into these essential components for running background tasks in .NET! ☕

What’s the Big Deal? 🎯

In any application, particularly those built with .NET, there’s often a need to run tasks in the background. These could be anything from sending emails, processing data, or running scheduled jobs. .NET provides two primary solutions for this: IHostedService and BackgroundService.

IHostedService: The Low-Level Hero 🛠️

IHostedService is an interface provided by .NET to create hosted services. It’s like the DIY kit of background tasks—offering flexibility but requiring a bit more effort. With IHostedService, you get two key methods:

  • StartAsync(CancellationToken cancellationToken): Called when the application starts.
  • StopAsync(CancellationToken cancellationToken): Called when the application stops.

When Should You Use IHostedService?

IHostedService is perfect for short-running tasks or when you need precise control over the service lifecycle. However, it does require you to manually implement the logic for starting and stopping your tasks.

Sample Code: Implementing IHostedService in C# 💻

public class ShortRunningWorker : IHostedService, IDisposable
{
    private Timer? _timer;

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));

        return Task.CompletedTask;
    }

    private void DoWork(object? state)
    {
        Console.WriteLine("Worker running at: {0}", DateTimeOffset.Now);
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _timer?.Change(Timeout.Infinite, 0);

        Console.WriteLine("Worker stopped at: {0}", DateTimeOffset.Now);

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();

        Console.WriteLine("Worker disposed at: {0}", DateTimeOffset.Now);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the DoWork method is called every second by a timer. When the application stops, the StopAsync method ensures that the timer is properly disposed of. Simple, but effective! 🎉

BackgroundService: The High-Level Champion 🏆

If IHostedService is the DIY kit, BackgroundService is the ready-made solution. BackgroundService is an abstract class that implements IHostedService and provides a higher-level abstraction for long-running tasks.

With BackgroundService, the key method to override is:

  • ExecuteAsync(CancellationToken cancellationToken): This method contains the logic for your background task and keeps running until the application shuts down.

Why Use BackgroundService?

BackgroundService simplifies the implementation of background tasks by handling common tasks internally, such as starting and stopping the service. This makes it ideal for long-running tasks where you want to reduce boilerplate code. 📉

Sample Code: Implementing BackgroundService in C# 🎉

public class LongRunningWorker : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            Console.WriteLine("Worker running at: {0}", DateTimeOffset.Now);

            await Task.Delay(1000, stoppingToken);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the ExecuteAsync method runs an infinite loop, logging the current time every second. The task continues running until the application shuts down. Easy peasy! 🍰

When to Use What? 🤷‍♂️

  • Use IHostedService when you need fine-grained control over the lifecycle of your background tasks. It’s perfect for short-running tasks or those that need to be carefully managed.

  • Use BackgroundService when you want to focus on the task itself and let .NET handle the service lifecycle. It’s ideal for long-running tasks where simplicity and less boilerplate are key. 🗝️

Wrapping It Up 🎁

To sum it all up, both IHostedService and BackgroundService are powerful tools in the .NET arsenal for running background tasks. Whether you need more control or prefer simplicity, there’s a solution that fits your needs. 🎯

If you found this guide helpful, don’t forget to share it with your fellow developers! And as always, happy coding! 👩‍💻👨‍💻

Top comments (0)