什么是 Worker Service(輔助角色服務)?
.NET Core 3.0 新增了 Worker Service 的新項目模板,可以編寫長時間運行的后台服務,並且能輕松的部署成 windows 服務或 linux 守護程序。
如果安裝的 vs2019 是中文版本,Worker Service 的項目名稱就變成了輔助角色服務。
IHostedService 接口方法:
StartAsync(CancellationToken) - 包含啟動后台任務的邏輯。
StopAsync(CancellationToken) - 主機正常關閉時觸發。
關於 BackgroundService
BackgroundService 是用於實現長時間運行的 IHostedService 的基類。
參考教程
- 開始創建worker service 項目
- Program.cs
- Worker.cs
- 依賴注入(DI)
- 重寫BackgroundService類的StartAsync、ExecuteAsync、StopAsync方法
- 不要讓線程阻塞worker類中重寫的StartAsync、ExecuteAsync、StopAsync方法
- 在Worker Service中運行多個Worker類
- 部署為Windows服務運行
- 部署作為Linux守護程序運行
案例 - 計時的后台任務
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Threading; using System.Threading.Tasks; namespace Demo_WorkerService_0320 { public class TimedHostedService : IHostedService, IDisposable { private int executionCount = 0; private readonly ILogger<TimedHostedService> _logger; private Timer _timer; public TimedHostedService(ILogger<TimedHostedService> logger) { _logger = logger; } public Task StartAsync(CancellationToken stoppingToken) { _logger.LogInformation("Timed Hosted Service running."); _timer = new Timer(DoWork, DateTime.Now.Ticks, TimeSpan.Zero, TimeSpan.FromSeconds(2)); return Task.CompletedTask; } private void DoWork(object state) { var count = Interlocked.Increment(ref executionCount); _logger.LogInformation($" *** Index = {count}, task start... *** "); Thread.Sleep(5 * 1000); _logger.LogInformation($" *** Index = {count}, task complete ***"); } public Task StopAsync(CancellationToken stoppingToken) { _logger.LogInformation("Timed Hosted Service is stopping."); _timer?.Change(Timeout.Infinite, 0); return Task.CompletedTask; } public void Dispose() { _timer?.Dispose(); } } }
Preview
參考資料
在 ASP.NET Core 中使用托管服務實現后台任務
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio
利用.NET Core中的Worker Service,來創建windows服務或linux守護程序
https://www.cnblogs.com/OpenCoder/p/12191164.html