DEV Community

Discussion on: C# Async Await, Simply

Collapse
 
glsolaria profile image
G.L Solaria

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!");
    });
}
Enter fullscreen mode Exit fullscreen mode

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!");
}
Enter fullscreen mode Exit fullscreen mode

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.

Collapse
 
nenadj profile image
Nenad

If you are worried about beginners than explain them !

Collapse
 
htissink profile image
Henrick Tissink

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 :)

Collapse
 
ronaldjenkins profile image
David Swayze

I keep reading a lot of posts when I first get into trouble. This is how I once reached this website (kodlogs.net/1/task-delay-vs-thread...) and got the desired solution. You can read this post as well as visit here. I think it will be very useful for you