csharp-background-service
Background Service 開發規範:BackgroundService、IHostedService、Channel Queue 模式與生命週期管理。當撰寫或審查 .NET 背景工作、排程任務或佇列處理邏輯時自動套用。
Skill by CloudyWing
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.
About
Reviews
Write a reviewNo 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
- 0.565score
ai-tool-discovery
CloudyWing
Use when the agent is about to explore a project or generate AI support artifacts and needs the local tool inventory or the state and rebuild path of existing…
SkillAFreshness: AClaude Code +9 - 0.565score
apply-fact-check
CloudyWing
依據事實校閱報告修改技術文件:以事實層為不可違反的約束,由改檔者負責表達層的措辭與行文連貫。Use when the user asks to apply fact-check results to a document, or to edit a document based on a previously…
SkillAFreshness: AClaude Code +9 - 0.564score
ai-context-index
CloudyWing
Use when an agent needs to create or update a project AI context index from the tools declared in AGENTS.md.
SkillAFreshness: AClaude Code +9 - 0.558score
browser-smoke
CloudyWing
瀏覽器煙霧驗證流程。當需要在修改 Web UI、頁面、路由、表單、互動、樣式、響應式版面或前端狀態後使用瀏覽器驗證,或使用者明確要求檢查畫面、console/network error、互動行為與 UI 修正結果時使用。
SkillAFreshness: AClaude Code +9 - 0.558score
api-smoke
CloudyWing
Web API 煙霧驗證流程。當需要在修改或開發 Web API 端點後驗證 API 行為,或使用者要求呼叫 Swagger、寫腳本測試 API、進行多情境 API 測試時使用。
SkillAFreshness: AClaude Code +9 - 0.555score
create-license-and-readme-link
CloudyWing
自動判斷專案屬性並推薦合適的開源授權,建立 LICENSE 檔案並將其連結補入 README.md 中。
SkillAFreshness: AClaude Code +9 - 0.555score
architecture-improvement
CloudyWing
以 Git hotspot 縮小分析範圍,使用 deletion test 篩選改善候選並產出架構改善報告。
SkillAFreshness: AClaude Code +9 - 0.555score
check-markdown
CloudyWing
當要求檢查 Markdown、修正格式或整理文件時使用。依據專案文件平台修正格式與排版問題。
SkillAFreshness: AClaude Code +9 - 0.555score
adr
CloudyWing
依決策門檻建立追加式 Architecture Decision Record,管理序號、狀態與被推翻的決策。
SkillAFreshness: AClaude Code +9 - 0.549score
codex-dispatch
CloudyWing
Codex 派工機制:依派工類型建立執行契約、以 codex exec 啟動 Codex、背景等待、取證並回收結果。當需要發動 codex、撰寫派遣單或執行派遣回收判定時使用。
SkillAFreshness: AClaude Code +9 - 0.524score
csharp-docs
CloudyWing
C# 文件與 XML 註解標準:強制使用標準標籤與用詞規範產生類別與方法的說明。Use when writing, reviewing, or generating XML documentation comments (///) in C# files, or when the user asks to add…
SkillBFreshness: BClaude Code +9 - 0.520score
codebase-design
CloudyWing
Use when 設計或審查模組邊界、Interface、Adapter、依賴方向與可測試性時。
SkillBFreshness: BClaude Code +9
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
- Repository
- github.com/CloudyWing/ai-dotfiles
- First seen
- Oct 24, 2026
- Last checked
- Oct 24, 2026
- Source
- GitHubgithub-graphql
More from CloudyWing
- 0.565score
ai-tool-discovery
CloudyWing
Use when the agent is about to explore a project or generate AI support artifacts and needs the local tool inventory or the state and rebuild path of existing…
SkillAFreshness: AClaude Code +9 - 0.565score
apply-fact-check
CloudyWing
依據事實校閱報告修改技術文件:以事實層為不可違反的約束,由改檔者負責表達層的措辭與行文連貫。Use when the user asks to apply fact-check results to a document, or to edit a document based on a previously…
SkillAFreshness: AClaude Code +9 - 0.564score
ai-context-index
CloudyWing
Use when an agent needs to create or update a project AI context index from the tools declared in AGENTS.md.
SkillAFreshness: AClaude Code +9 - 0.558score
api-smoke
CloudyWing
Web API 煙霧驗證流程。當需要在修改或開發 Web API 端點後驗證 API 行為,或使用者要求呼叫 Swagger、寫腳本測試 API、進行多情境 API 測試時使用。
SkillAFreshness: AClaude Code +9 - 0.558score
browser-smoke
CloudyWing
瀏覽器煙霧驗證流程。當需要在修改 Web UI、頁面、路由、表單、互動、樣式、響應式版面或前端狀態後使用瀏覽器驗證,或使用者明確要求檢查畫面、console/network error、互動行為與 UI 修正結果時使用。
SkillAFreshness: AClaude Code +9 - 0.555score
adr
CloudyWing
依決策門檻建立追加式 Architecture Decision Record,管理序號、狀態與被推翻的決策。
SkillAFreshness: AClaude Code +9
Cite this page
csharp-background-service skill. Agent Mart. https://agentmart.dev/skills/cloudywing-csharp-background-service (last updated 2026-10-24)