https://blog.yaseerarafat.com/net-background-servi...
बनाया गया: 11 जनवरी 2026
का उपयोग करके उत्तर दिया गया GPT-5.2 Thinking द्वारा Chat01
बनाया गया: 11 जनवरी 2026
का उपयोग करके उत्तर दिया गया GPT-5.2 Thinking द्वारा Chat01
I can’t give you the full text of that page, because it’s a Medium “member-only story” and the content beyond the intro is not accessible from the public page view I can fetch. What I can do right now is:
If you want a true “full detail” breakdown of that exact article, paste the article body here (or share a non-paywalled copy) and I’ll go section-by-section.
From the accessible excerpt, the article sets up this scenario: a “quiet” .NET Worker Service doing background tasks (queues, emails, sync, cleanup) suddenly causes massive CPU spikes, autoscaler churn, and a surprise cloud bill—arguing that the real culprit isn’t C#, but “unexamined assumptions.” (Medium)
The first assumption it calls out is:
“Background Services are just console apps with loops”—the typical
while(true)+ delay pattern that feels simple but hides operational pitfalls. (Medium)
That’s all that’s visible on the page without member access. (Medium)
Below are the most common real failure modes behind that “it was fine until it wasn’t” story—grounded in how Hosted Services / BackgroundService actually behave.
If you schedule work on a timer (or System.Threading.Timer) and the work sometimes takes longer than the interval, you can get overlapping runs. With System.Threading.Timer, callbacks can run concurrently; the callback “should be reentrant,” and it can execute simultaneously on multiple ThreadPool threads if the interval is shorter than the callback duration. (Microsoft Learn)
Even Microsoft’s hosted-services guidance warns that a timer doesn’t wait for prior executions to finish, so the naive timer approach may not fit many scenarios. (Microsoft Learn)
What that looks like in production
Polling loops tend to do some work every tick (wakeups, queries, logs, allocations). If you have multiple instances (Kubernetes, App Service scale-out), you multiply that baseline cost by replica count.
Microsoft explicitly lists “polling a database looking for changes” as a background-task example—but that pattern needs careful design to avoid the scaling trap. (Microsoft Learn)
A hosted service is commonly registered as a singleton-ish long-lived service. No DI scope is created for a hosted service by default, so if you need scoped services, you must create a scope for each unit of work. (Microsoft Learn)
If you don’t:
Hosted services are coordinated with app start/stop; StartAsync/StopAsync are part of the contract. (Microsoft Learn)
If you ignore the CancellationToken (or you Task.Delay(...) without the token), shutdown becomes slow or abrupt, which can cause retries, duplicates, and more compute.
Also worth knowing: in .NET 10, BackgroundService changed so all of ExecuteAsync runs on a background thread; previously the synchronous part (before the first await) ran on the main thread and could block startup. (Microsoft Learn)
That matters if your worker does heavy synchronous setup in ExecuteAsync.
If you want periodic work without overlap, PeriodicTimer is often a better mental model because you explicitly await ticks. The docs note:
That coalescing can be a feature (prevents “catch-up storms”), but you need to be aware of it.
This is the practical “fix list” that typically eliminates the cost spikes:
If you can, drive work from a queue/event stream instead of “check every N seconds.” When you must poll, add:
Make concurrency a knob:
Create and dispose a scope each iteration (or each message) so scoped resources don’t accumulate. (Microsoft Learn)
If your timer mechanism can overlap, assume it will.
System.Threading.Timer, design callback to be reentrant and safe under concurrency (Microsoft Learn)Honor stoppingToken everywhere.
Also be aware you can configure shutdown timeouts (example shown in Microsoft’s microservices/host guidance). (Microsoft Learn)
csharpusing Microsoft.Extensions.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System.Threading; public interface ICatalogSyncJob { Task RunOnceAsync(CancellationToken ct); } public sealed class CatalogSyncWorker : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger<CatalogSyncWorker> _logger; private readonly PeriodicTimer _timer = new(TimeSpan.FromSeconds(10)); public CatalogSyncWorker(IServiceScopeFactory scopeFactory, ILogger<CatalogSyncWorker> logger) { _scopeFactory = scopeFactory; _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (await _timer.WaitForNextTickAsync(stoppingToken)) { try { await using var scope = _scopeFactory.CreateAsyncScope(); var job = scope.ServiceProvider.GetRequiredService<ICatalogSyncJob>(); await job.RunOnceAsync(stoppingToken); } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { // normal shutdown } catch (Exception ex) { _logger.LogError(ex, "Background job failed; backing off"); await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); } } } public override void Dispose() { _timer.Dispose(); base.Dispose(); } }
Why this shape matches the official guidance:
PeriodicTimer is an async “wait for tick” primitive (Microsoft Learn)Paste the article text here (even in chunks), and I’ll:
Help me understand volume in action with candel sticks
Sure — before we dive in, quick check so I explain it at the right level:
Are you trading/investing (stocks/crypto/forex), and on what timeframe (1m/5m/day)?
Swing trading
Nice — swing trading is a great timeframe for “volume + candlesticks” because you can actually see who’s in control (buyers vs sellers) without the noise of 1-minute charts.
Let’s build this in a way you can use tomorrow.
Think of volume as the “effort” behind the candle.
Real breakout: price breaks resistance AND volume is higher than recent average → odds improve that the move follows through.
Fake breakout: price pokes above resistance but volume is meh → often reverses back into the range.
Your move: On the breakout candle, compare volume to the last ~20 bars (mentally: “is it clearly above normal?”).
Look for:
Story: sellers dumped hard, but buyers absorbed it and pushed price back up off the lows.
Your move: Mark the low of that wick. If price holds above it over the next few candles, that low becomes a key risk level.
Story: The move is weak; market may be setting up for the opposite direction.
Your move: When you see low-volume drift into a key level, wait for the next strong candle+volume to confirm direction.
Candle has:
Story: heavy buying and selling occurred, but price didn’t progress → one side is absorbing the other.
Your move: Treat that zone like a “wall.” A clean break later (with volume) is meaningful.
Imagine price breaks above resistance with a strong green candle, but volume is lower than the last 10–20 candles.
As a swing trader, what does that suggest to you: strong breakout or possible fakeout?
Invalidation process chart
Here’s a swing-trader “invalidation process chart” you can use with candlesticks + volume. The goal is simple: define exactly what has to happen for your idea to be wrong, and then act fast when it does.
textSTART │ ├─► 1) Identify setup type │ A) Breakout B) Pullback (trend) C) Reversal at S/R │ ├─► 2) Write the thesis in 1 sentence │ "If price holds above/below X, it should move toward Y." │ ├─► 3) Mark the "line in the sand" (price level) │ - Breakout: prior resistance/support + breakout candle structure │ - Pullback: higher low / lower high area or moving average zone │ - Reversal: the wick-low (for long) or wick-high (for short) │ ├─► 4) Define HARD invalidation (exit no matter what) │ Usually: a candle CLOSE beyond your line in the sand │ (not just an intraday wick), OR the wick is broken if using wick-based stop. │ ├─► 5) Define VOLUME invalidation (the "uh-oh" signal) │ "If price does the wrong thing WITH high volume → exit faster." │ ├─► 6) Add TIME invalidation (prevents slow bleeding) │ "If no progress after N candles/days → exit or reduce." │ └─► 7) Execute: either HOLD, REDUCE, or EXIT based on which invalidation triggers END
Entry idea: price breaks resistance and continues.
Hard invalidation (classic):
Volume invalidation (faster exit):
Extra (good filter):
Entry idea: trend is up; pullback is a reset before the next leg.
Hard invalidation:
Volume invalidation:
Candlestick invalidation clue:
Entry idea: sellers are exhausting at support; buyers absorb.
Hard invalidation (most common):
Volume invalidation:
Time invalidation (important on reversals):
Use a two-tier system:
Before entry
After entry
If “yes” → reduce/exit per your rules.
If you tell me what chart timeframe you use for swing trading (daily only vs 4H + daily), I’ll tailor the chart into exact numbers like: “invalidate on a daily close under X” vs “invalidate on 4H close under X, but only exit fully on daily close.”