.netwindowsservicehostsc.exe

Cannot run .net Windows Service as Windows host - sc.exe (The service did not respond to the start or control request in a timely fashion)


I wrote my own program with the intention of running it as a background service (Windows Service), not as an application.

I created default program from wizard (https://learn.microsoft.com/en-us/dotnet/core/extensions/workers), changed it a little but when I wanted to run sc.exe (of course in the PowerShell Admin) the program was all the time marked as "Starting". Also tried Win+R -> services.msc (or type Services in Windows search bar) and I couldn't make my program marked as Running.

There were no issues in the Windows Event viewer (Windows Logs -> Application)

sc.exe create "MyService" binPath= "<Target location>\MyProgram.exe"

sc.exe start "MyService"

sc.exe query "MyService" // check service status (Starting, Running, Stopped)

sc.exe stop "MyService"

sc.exe delete "MyService"

I could run it in terminal, but couldn't run it as sc.exe. I even created a completly new program (Add New Project -> Worker Service with SDK 8.0 .net) and still:

The service did not respond to the start or control request in a timely fashion.

I tried changing Windows startup timeout settings, registry fix, nothing helped.


Solution

  • don't change anything in the Windows settings. There is a problem with your Program.cs.

    Just change:

    var builder = Host.CreateApplicationBuilder(args);
    builder.Services.AddHostedService<Worker>();
    
    var host = builder.Build();
    host.Run();
    

    to

    var builder = Host.CreateDefaultBuilder(args)
        .ConfigureServices(services =>
        {
            services.AddHostedService<Worker>();
        })
        .UseWindowsService(options =>
        {
            options.ServiceName = "myName";
        });
    
    var host = builder.Build();
    host.Run();