Thread.Sleep vs Task.Delay in C#: Which to Use and Why (video)
Thread.Sleep blocks a thread; await Task.Delay frees it. Learn the difference, why Thread.Sleep hurts ASP.NET Core throughput, how to cancel a delay, and better options for retries and polling.
Transcript
Thread.Sleep vs Task.Delay in C#: Which to Use and Why. Here's the short version.
Thread.Sleep and Task.Delay both make code wait, but they wait in completely different ways. Thread.Sleep holds on to the thread and does nothing with it. await Task.Delay gives the thread back and resumes later.
What each one does. Thread.Sleep(1000) blocks the current thread for one second. Nothing else can run on it. await Task.Delay(1000) schedules a timer and returns the thread to the pool. Task.Delay without await does nothing useful: it creates a task that nobody waits for.
Here's an example: Each retry blocks a thread-pool thread.
Why Thread.Sleep hurts servers. ASP.NET Core serves requests from the thread pool. await Task.Delay uses no thread while it waits, so the same server can handle thousands of waiting requests.
Better tools for common cases. Retries: use a resilience library such as Polly or Microsoft.Extensions.Http.Resilience instead of hand-written loops. Polling every N seconds: use PeriodicTimer in a BackgroundService (await timer.WaitForNextTickAsync(ct)). Tests: avoid fixed sleeps; wait for the condition you expect, or inject a TimeProvider and advance time.
Want to find these issues in your own code? Connect your GitHub repository to CodeInspector. You'll get findings with the file, line, severity, and a recommended fix, plus HTML and PDF reports for your team. Start free at codeinspector.app.
More videos
- CodeInspector product demo (0:54)
- CodeInspector Now Works Inside Claude: Scan and Fix Code in One Conversation (video) (1:20)
- throw vs throw ex in C#: Why throw ex Destroys Your Stack Trace (video) (1:22)
- Task.Result and .Wait() Deadlocks in C#: Why Sync-over-Async Hangs (video) (1:47)
- ILogger Best Practices in .NET: Structured Logging That Helps You Debug (video) (1:20)
- TypeScript any vs unknown: Why any Turns Off the Type Checker (video) (1:16)