Home > Net >  .NET Core 6.0 service cannot be started via services console (error 1053)
.NET Core 6.0 service cannot be started via services console (error 1053)

Time:11-06

I created a new windows service "WorkerService" using the worker service template in VS 2022, platform is .NET 6.

The program itself works, showing a log "Worker running..." every second.

I published it to C:\WorkerService and registered it via Powershell command:

New-Service -Name "WorkerService1" -BinaryPathName "C:\WorkerService\WorkerService1.exe"

Starting the new service via the services console fails after 30 seconds with the error 1053 and message "the service did not respond to the start or control request in a timely fashion". The event log does only displays two error entries, both claiming that the service did not respond timely

Running the service directly via powershell is no problem, however.

In order to track down the issue, I enriched the startup code with a method to log the different steps taken:

using WorkerService1;


internal class Program
{
    private static StreamWriter? StreamWriter { get; set; }

    private static void Log(string message)
    {
        StreamWriter.WriteLine($"{DateTime.Now}: {message}");
        StreamWriter.Flush();
    }

    private static async Task Main(string[] args)
    {
        using (StreamWriter = new StreamWriter("serviceLog.txt"))
        {
            Log("Starting up...");
            try            
            {
                Log("Building...");
                IHost host = Host.CreateDefaultBuilder(args)
                .ConfigureServices(services =>
                {
                    services.AddHostedService<Worker>();
                }).Build();
                Log("Running...");
                await host.RunAsync();
            }
            catch (Exception e)
            {
                Log(e.ToString());
                throw;
            }
            Log("Shutting down...");
        }        
    }
}

This writes down the expected lines in the text file when executed interactively, but has no effect whatsoever when trying again to start the service via the services console. The code does not seem to be reached in this scenario.

The Worker class is the unmodified version of the template:

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;

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

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(1000, stoppingToken);
        }
    }
}

What am I missing?

CodePudding user response:

To host your service in a Windows Service you need a call to UseWindowsService.
Setting the service name is optional.

From the documentation - Create Windows Service using BackgroundService:

The UseWindowsService extension method configures the app to work as a Windows Service.

You'll need a NuGet package reference to Microsoft.Extensions.Hosting.WindowsServices.

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<Worker>();
    })
    .UseWindowsService(o => o.ServiceName = "Workerservice1")
    .Build();
  • Related