Skip to content
Agentmart
Submit a tool

csharp-background-service

Background Service 開發規範:BackgroundService、IHostedService、Channel Queue 模式與生命週期管理。當撰寫或審查 .NET 背景工作、排程任務或佇列處理邏輯時自動套用。

Skill by CloudyWing

IndexedMIT
Write a review

Install

Works with Claude Code, Claude apps, Codex, Cursor, Gemini CLI, GitHub Copilot, VS Code, OpenCode, Goose, Windsurf. Read the repository before you give any tool access to your data.

npx agentmarket install skill/cloudywing-csharp-background-service

Asks which of your tools to add it to (Claude Code, Codex, Cursor, VS Code, Windsurf, Gemini CLI, Claude Desktop) and shows the change first. See https://agentmart.dev/cli.

Get the weekly diff

The weekly diff: one email a week with new agent tools, notable updates and grade changes, plus security alerts for tools you follow. Double opt-in, one-click unsubscribe.

We use your email only for this newsletter. Privacy

About

Background Service 開發規範:BackgroundService、IHostedService、Channel Queue 模式與生命週期管理。當撰寫或審查 .NET 背景工作、排程任務或佇列處理邏輯時自動套用。

No reviews yet. Installed it? Reviews come from verified installers only. How reviews work

Permissions

What this skill can do and what it asks for, from its SKILL.md. Checked Oct 25, 2026.

Tools
No tools found
Secrets
None asked for
Install scripts
None found

Network hosts it talks to 1

  • codeload.github.com · found in install command

Files it touches

  • ~/.claude/skills/csharp-background-service

What's inside

Skill name
csharp-background-service
Description
Background Service 開發規範:BackgroundService、IHostedService、Channel Queue 模式與生命週期管理。當撰寫或審查 .NET 背景工作、排程任務或佇列處理邏輯時自動套用。
License
MIT
Instructions
304 lines in SKILL.md · view on GitHub

Files (1)

  • SKILL.md

SKILL.md (first lines)

# Background Service 開發規範

## 選型指引(Crucial)

| 基底類別 | 適用情境 |
| --- | --- |
| `BackgroundService` | 長期執行的迴圈式工作(如輪詢、佇列消費) |
| `IHostedService` | 需精確控制啟動 / 停止順序的初始化或清理任務 |

- `BackgroundService` 繼承自 `IHostedService`,提供 `ExecuteAsync` 抽象方法,適合大多數場景。
- `IHostedService` 適合在 `StartAsync` 中做一次性初始化(如預熱快取、建立連線),不需要持續迴圈;僅限資料量與耗時有界、具取消處置且為 Host 就緒必要條件的工作。一般或無界外部 I/O 預熱應移至可追蹤且可取消的背景路徑。

## 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.FromMinutes(5), stoppingToken).ConfigureAwait(false);
        }

        logger.LogInformation("OrderSyncService 已停止");
    }
}
```

### 關鍵規範

- **CancellationToken**:`ExecuteAsync` 的 `stoppingToken` 必須傳遞給所有非同步操作與 `Task.Delay`。
- **例外處理(Crucial)**:`ExecuteAsync` 中的未處理例外會導致整個 Host 停止(.NET 6+ 預設行為)。迴圈式工作**必須**在 `while` 內部 try-catch,記錄錯誤後繼續下次迴圈。
- **OperationCanceledException**:`stoppingToken` 觸發時,`Task.Delay` 和非同步操作會拋出此例外。使用 `when (stoppingToken.IsCancellationRequested)` 過濾,避免記錄為錯誤。

### Scoped 服務存取(Crucial)

BackgroundService 註冊為 Singleton,**不能**直接注入 Scoped 服務(如 DbContext)。必須透過 `IServiceScopeFactory` 建立 Scope。

```csharp
// ❌ 錯誤:直接注入 Scoped 服務
public class MyWorker : BackgroundService {
    public MyWorker(AppDbContext db) { /* ... */ }
}

// ✅ 正確:透過 IServiceScopeFactory
public class MyWorker : BackgroundService {
    private readonly IServiceScopeFactory scopeFactory;

    public MyWorker(IServiceScopeFactory scopeFactory) {
        this.scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
        await using AsyncServiceScope scope = scopeFactory.CreateAsyncScope();
        AppDbContext db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    }
}

// ✅ 正確:EF Core 場景優先使用 IDbContextFactory
public class MyWorker : BackgroundService {
    private readonly IDbContextFactory<AppDbContext> factory;

    public MyWorker(IDbContextFactory<AppDbContext> factory) {
        this.factory = factory;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
        await using AppDbContext db = await factory.CreateDbContextAsync(stoppingToken)
            .ConfigureAwait(false);
    }
}
```

## IHostedService 實作規範

```csharp
public class CacheWarmupService : IHostedService {
    private readonly IServiceScopeFactory scopeFactory;
    private readonly IMemoryCache cache;
    private readonly ILogger<CacheWarmupService> logger;

    public CacheWarmupService(
        IServiceScopeFactory scopeFactory,
        IMemoryCache cache,
        ILogger<CacheWarmupService> logger
    ) {
        this.scopeFactory = scopeFactory;
        this.cache = cache;
        this.logger = logger;
    }

    public async Task StartAsync(CancellationToken cancellationToken) {
        logger.LogInformation("開始預熱快取");

        await using AsyncServiceScope scope = scopeFactory.CreateAsyncScope();
        IProductRepository repository = scope.ServiceProvider
            .GetRequiredService<IProductRepository>();

From CloudyWing/ai-dotfiles, MIT.

More from CloudyWing/ai-dotfiles

Signals

Stars
0
Forks
0
Open issues
0
Last commit (this folder)
Oct 10, 2026 (19 days ago)

From GitHub (fetched Oct 24, 2026).

Details

License
MIT
First seen
Oct 24, 2026
Last checked
Oct 24, 2026

More from CloudyWing

Cite this page

csharp-background-service skill. Agent Mart. https://agentmart.dev/skills/cloudywing-csharp-background-service (last updated 2026-10-24)