This is my whole service
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;
var host = Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
})
.Build();
await host.RunAsync();
public class Worker : BackgroundService
{
public Worker()
{
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(1000, stoppingToken);
}
}
}
I register it with sc.exe create and I run it with sc.exe start. I am running it with admin access in cmd. I keep getting this error: The service did not respond to the start or control request in a timely fashion.
What am I doing wrong?
You need to configure your app to be run as a windows service, first need to add this package:
Microsoft.Extensions.Hosting.WindowsServices
And in the Program.cs
:
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddWindowsService(options =>
{
options.ServiceName = ".NET Joke Service";
});
builder.Services.AddHostedService<Worker>();
Here is a very good guideline for creating windows service by Microsoft:
https://learn.microsoft.com/en-us/dotnet/core/extensions/windows-service