Search code examples
c#.net.net-corebackground-service

IHostedService always create two processes


I'm writing a HostedService and always when I run it, it create two times the process to execute (I've checked the logs and there are two with almost the same time when should be 5 secondos each) I've followed the oficial docs.

https://learn.microsoft.com/es-es/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2&tabs=visual-studio

this is an example of my HostedService

internal class TimedHostedService : IHostedService, IDisposable
{
    private readonly ILogger _logger;
    private Timer _timer;

    public TimedHostedService(ILogger<TimedHostedService> logger)
    {
        _logger = logger;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Background Service is starting.");

        _timer = new Timer(DoWork, null, TimeSpan.Zero, 
            TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        _logger.LogInformation("Timed Background Service is working.");
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Background Service is stopping.");

        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }

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

I add the service like:

services.AddHostedService<TimedHostedService>();

Solution

  • You should get two different threads, the Host and HostedService, might appear as the same process running two times depending on the OS and the application used to inspect the running processes.