re: C# Async Await, Simply VIEW POST

FULL DISCUSSION
 

I understand why you are using Thread.Sleep (to mimic doing some CPU intensive work) but I fear it will also give beginners the wrong impression about using Thread.Sleep in tasks to delay work. I think instead of ...

public static async Task WorldDomination()
{
    await Task.Run(() =>
    {
        Thread.Sleep(6000);
        Console.WriteLine("World Domination Achieved!");
    });
}

If you need to delay before doing something in a task ...

public static async Task WorldDomination()
{
    await Task.Delay(6000);
    Console.WriteLine("World Domination Achieved!");
}

If you Thread.Sleep in many running tasks, performance may suffer. If you do it to excess, work may have to be queued waiting for all the sleeping threads to wake and finish executing their work. At the very worst you could get out of memory exceptions.

Like I said I understand why you chose to use Thread.Sleep for your example but beginners shouldn't think that using Thread.Sleep in tasks is good practice.

Helping others understand async/await is no mean feat. Good on you for giving it a go.

 

You make a good point. Awaiting a Task.Delay is much better - Thread.Sleep was just used for the illustration. I'll fix it when I get the chance :)

 

If you are worried about beginners than explain them !

code of conduct - report abuse