Proper way to implement a never ending task. Timers vs Task
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Long-running background work is common in servers, agents, and desktop applications, but a "never ending task" is easy to implement badly. The real requirements are usually simple: run work repeatedly, avoid overlapping executions, support shutdown, and surface failures. In modern C#, a cooperative async loop is usually the right default, while raw timers are better reserved for simpler callback-style work.
Why Timers Often Cause Trouble
A timer looks attractive because it is short to write:
This works for trivial callbacks, but it has a major weakness: the timer does not care whether the previous callback has finished. If the work takes longer than the interval, callbacks can overlap and compete for the same resources.
That is fine for lightweight metrics or heartbeat updates. It is much less fine for polling a queue, writing files, or calling an external API where concurrency must be controlled.
Prefer An Async Loop For Repeated Work
If the job has real business logic, a dedicated async loop is easier to reason about. You wait, run one iteration, handle errors, and honor cancellation.
In an ASP.NET Core service, BackgroundService plus PeriodicTimer is a strong pattern:
This design gives you exactly one active iteration at a time. It also makes shutdown predictable because the loop listens to the cancellation token.
When A Plain Task Loop Is Enough
If you are not inside a hosted application, you can still use the same idea with a regular async method:
This is often enough for command-line tools, daemons, or integration utilities. The important part is that the delay happens after the work finishes, so iterations cannot pile up.
Choosing The Right Tool
Use a timer when the callback is small, stateless, and safe to overlap, or when you explicitly want time-based triggering regardless of callback duration.
Use an async loop when the job needs backpressure, cancellation, retries, structured logging, or one-at-a-time execution. That is the more robust default for production services.
If you need repeated scheduling with no overlap, PeriodicTimer is often a better fit than the older Timer API because it integrates naturally with async code.
Common Pitfalls
The biggest mistake is writing while (true) without a cancellation path. That makes shutdown hard and usually turns testing into a mess.
Another common problem is allowing overlapping timer callbacks. If each callback touches shared state, subtle race conditions follow quickly.
Swallowed exceptions are also dangerous. A background loop that fails silently can stop doing useful work while the process appears healthy.
Finally, avoid blocking calls such as .Wait() or .Result inside async background code. They increase the risk of deadlocks and thread starvation.
Summary
- Raw timers are fine for simple periodic callbacks, but they can overlap.
- An async loop is usually the better model for long-running background work.
- '
PeriodicTimerworks well withasyncand helps keep one iteration active at a time.' - Always support cancellation, logging, and exception handling.
- Prefer clarity and predictable execution over the shortest possible implementation.
Related reading
- Pros and cons of async/await
- Protractor async/await UnhandledPromiseRejectionWarning Unhandled promise rejection
- Proving correctness of multithread algorithms
- PThread vs boostthread?
- Python - Flask-SocketIO send message from thread not always working
- Python - How can I make this code asynchronous?
- Python - Single thread executor already being used, would deadlock
- Python 3.6 async aioodbc blocking
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.