Introduction
ASP.NET Core 3 adds a very interesting feature Worker Service . He is an ASP.NET Core template, he allows us to create a managed long-running background services that realization IHostedService background task logical interfaces, he was to become "Managed services." At the same time they can be deployed to windows in Windows services, as well as Linux daemon.
Creating a hosting service
Our new commands via the command line interface dotnet. Create a file called by the following code customWorker of WorkerService applications.
dotnet new worker -o customWorker
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WorkerServiceDemo
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
}
Worker:
BackgroundService is achieved IHostedService base class. Call ExecuteAsync (CancellationToken) to run background services. Implementation returns a Task, which represents the entire lifetime of back-office services. In ExeuteAsync (for example, by calling await) before, do not start any other service. Avoid ExecuteAsync execution time blocking initialization. StopAsync (CancellationToekn) host block waiting complete ExecuteAsync .
When you call IHostedService.StopAsync, it will trigger the cancellation token. When the excitation Cancel to close the service token normal, ExecuteAsync implementation should be completed immediately. Otherwise, the service will not shut down properly after closing out.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace WorkerServiceDemo
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
public override async Task StartAsync(CancellationToken cancellationToken)
{
await base.StartAsync(cancellationToken);
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
public override void Dispose()
{
}
}
}
Extension methods already in use AddHostedService IHostBuilder.ConfigureServices register the service (Program.cs).
services.AddHostedService<Worker>();
WorkerServices to deploy Windows Services
Installation WorkerServices template
Use UseWindowsService extension method IHostBuilder
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WorkerServiceDemo
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
}).UseWindowsService(); ;
}
}
}
Now we can deploy our windows served.
Publishing
- Use tools sc.exe
- Exe files directly deployment
Released Windows Service
dotnet restore
dotnet publish
sc.exe deployment
sc.exe create DemoWorker binpath= publish\xxxx.exe
sc.exe start WorkerServicesName
Exe file deployment
WorkerServicesName.exe install
WorkerServicesName.exe start
Use sc.exe stop and delete
sc.exe stop WorkerServicesName
sc.exe delete WorkerServicesName
Non-stop and delete sc.exe
WorkerServicesName stop
WorkerServicesName uninstall
Reference
https://github.com/hueifeng/BlogSample/tree/master/src/WorkerServiceDemo