← ClaudeAtlas

csharp-background-servicelisted

Background Service 開發規範:BackgroundService、IHostedService、Channel Queue 模式與生命週期管理。當撰寫或審查 .NET 背景工作、排程任務或佇列處理邏輯時自動套用。
CloudyWing/ai-dotfiles · ★ 0 · AI & Automation · score 73
Install: claude install-skill CloudyWing/ai-dotfiles
# Background Service 開發規範 ## 選型指引(Crucial) | 基底類別 | 適用情境 | | --- | --- | | `BackgroundService` | 長期執行的迴圈式工作(如輪詢、佇列消費) | | `IHostedService` | 需精確控制啟動 / 停止順序的初始化或清理任務 | - `BackgroundService` 繼承自 `IHostedService`,提供 `ExecuteAsync` 抽象方法,適合大多數場景。 - `IHostedService` 適合在 `StartAsync` 中做一次性初始化(如預熱快取、建立連線),不需要持續迴圈。 ## BackgroundService 實作規範 ### 基本結構 ```csharp public class OrderSyncService : BackgroundService { private readonly IServiceScopeFactory scopeFactory; private readonly ILogger<OrderSyncService> logger; public OrderSyncService(IServiceScopeFactory scopeFactory, ILogger<OrderSyncService> logger) { this.scopeFactory = scopeFactory; this.logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { logger.LogInformation("OrderSyncService 已啟動"); while (!stoppingToken.IsCancellationRequested) { try { await using AsyncServiceScope scope = scopeFactory.CreateAsyncScope(); IOrderRepository repository = scope.ServiceProvider .GetRequiredService<IOrderRepository>(); await repository.SyncPendingOrdersAsync(stoppingToken).ConfigureAwait(false); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { // 正常停止,不記錄為錯誤 } catch (Exception ex) { logger.LogError(ex, "訂單同步發生錯誤,將在下次迴圈重試"); } await Task.Delay(TimeSpan.