Search code examples
.netc#-4.0task-parallel-librarydelaythread-sleep

Call Thread.Sleep from the Task


Is it correct to use Thread.Sleep() inside the task. Or is only a timer (Task.Delay() in .Net 4.5 and latter) used with task? Or maybe another approaches exist.


Solution

  • You can use Thread.Sleep inside a task. But in most situations I'd prefer to use await Task.Delay which does not block the thread.

    If you're using Task.Run (which uses a ThreadPool thread), then you should try not to block the thread. As it is a shared thread, there may be other code waiting to run.

    I would still use Thread.Sleep(0) when I'm done using the thread, to yield the processor and give up your time slice.