wasAsked.

difference between thread.sleep vs task.delay

PwC · Full Stack Developer · technical

Published

Year not specified · C#

Community answers

Posted by wasAsked editorial collection

Thread.Sleep blocks the current thread; Task.Delay creates a task that completes after a time, letting you wait asynchronously without blocking a thread. Thread.Sleep(milliseconds) - Synchronous: the thread is paused and can do nothing else during the wait. - In a UI app, the interface freezes. In ASP.NET Core, a thread-pool thread is held idle, reducing scalability and potentially causing thread-pool starvation under load. - Cannot be cancelled (except by interrupting the thread, which is rarely appropriate). - Use only in rare synchronous scenarios, such as a dedicated background thread or simple console tools. await Task.Delay(milliseconds, cancellationToken) - Asynchronous: internally uses a timer; no thread is blocked during the delay. - The calling method returns control to its caller, and continues after the delay. - Supports cancellation through CancellationToken. - Must be awaited; calling Task.Delay without await does not pause anything. Example: // Bad in an API: blocks a thread for 2 seconds public IActionResult Slow() { Thread.Sleep(2000); return Ok(); } // Good: the thread is free during the wait public async Task<IActionResult> Slow(CancellationToken ct) { await Task.Delay(TimeSpan.FromSeconds(2), ct); return Ok(); } Typical uses of Task.Delay - Retry with backoff: await Task.Delay(TimeSpan.FromMilliseconds(200 * Math.Pow(2, attempt)), ct); - Polling loops in background services: while (!stoppingToken.IsCancellationRequested) { await DoWorkAsync(stoppingToken); await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); } - Timeouts combined with Task.WhenAny. - Simulating latency in tests or demos. Common mistakes - Using Task.Delay(...).Wait() — this blocks just like Thread.Sleep. - Forgetting await. - Using delays to "fix" race conditions instead of proper synchronisation. Related: PeriodicTimer (.NET 6+) is a clean way to run periodic async work: while (await timer.WaitForNextTickAsync(ct)) { ... }. In tests, TimeProvider (.NET 8) lets you control time instead of really waiting.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics