Create a .Net Worker service project in Visual Studio 2022 or 2019 and name it as you want. Worker service started in Visual Studio 2019, and it works in the latest versions. Worker service is a background service that runs as a service and executes some continuous background tasks.
Worker.cs
namespace MyWorkerService
{
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)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
}
await Task.Delay(1000, stoppingToken);
}
}
}
}
To install the Worker service in Windows, the background service installs the below-mentioned Hosting package from the Nuget package.
Microsoft.Extensions.Hosting.WindowsServices
Add the code below to the program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<YourWorkerService>();
});
Build and Publish the worker service project and make sure MyWorkerService.exe is placed inside the publish folder. Then, Open the Command prompt with administrative privileges and execute the mentioned command lines.
sc.exe create MyWorkerService binpath=C:\MyWorkerService\MyWorkerService.exe
sc.exe start MyWorkerService
In case of any error, if you want to delete or stop a service, follow the command lines.
sc.exe delete MyWorkerService
sc.exe stop MyWorkerService
To ensure the smooth running of the worker service, open a service from the start of a window, check the name of the service (Example: MyWorkerService), and confirm the service is running.
Output