-3

Can I assume that doTask and doTask2 makes the same job and might be replaced in code?

    public async static void doTask()
    {
        await Task.Delay(TimeSpan.FromSeconds(5));
    }


    public async static void doTask2()
    {
        await Task.Factory.StartNew(() =>
        {
            Thread.Sleep(TimeSpan.FromSeconds(5));
        });
    }

According my experiments both functions acts the same.

vico
  • 17,051
  • 45
  • 159
  • 315
  • 2
    The first one allows the thread servicing the task to return to the operating system. The second blocks the thread. The first is better. –  Nov 09 '17 at 16:07
  • 2
    Actually really [different](https://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Task.cs,34b191a243434f6a) – Filip Cordas Nov 09 '17 at 16:10
  • 1
    As an aside, [`async void` considered harmful](https://stackoverflow.com/q/12144077/4137916). Avoid it even in examples. – Jeroen Mostert Nov 09 '17 at 16:15

1 Answers1

0

One very very important difference between those is that Thread.Sleep() is blocking thread for a duration, means thread won't be available to thread pool, while Task.Delay() creates a task and immediately release thread, so that other tasks can use that thread.

Thread.Sleep may easily lead to thread starvation.

To demonstrate (notice I have changed return type to Task):

static void Main(string[] args)
{
    Task.WaitAll(Enumerable.Range(0, 1000).Select(o => doTask()).ToArray());
    Console.WriteLine("1");
    Task.WaitAll(Enumerable.Range(0, 1000).Select(o => doTask2()).ToArray());
    Console.WriteLine("2");
}

public async static Task doTask() => await Task.Delay(TimeSpan.FromSeconds(1));
public async static Task doTask2() => await Task.Factory.StartNew(() => Thread.Sleep(TimeSpan.FromSeconds(1)));

You will see 1 pretty quickly, but it takes a lot of time (several minutes on my 8 core CPU) for 2 to appears.

Rule of thumbs: using threads - use Thread.Sleep, using tasks - stick to Task.Delay.

Sinatr
  • 20,892
  • 15
  • 90
  • 319
  • Add to this thread switching and CPU cache invalidation - if the method did useful job, `Sleep()` would force a thread switch *and* empty the CPU's cache from the thread's data – Panagiotis Kanavos Nov 09 '17 at 16:34