Call Thread.Sleep from the Task

SerG picture SerG · Dec 16, 2013 · Viewed 9.1k times · Source

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.

Answer

dcastro picture dcastro · Dec 16, 2013

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.