0

I'm new to async/await and I have tried to create a responsive clock as a demo. the clock worked fine, but when I tried to get it into asynchronous function and awaited the delay it stopped working, displaying only the time in which it ran. here is the code:

public static async void clock ()
   {
      while (true)
         {
            Console.WriteLine(DateTime.Now.ToString());
            await Task.Delay(1000);
            Console.Clear();
         }
   }

and the main is just:

clock();

edit: its seems like the App doesn't run thro the stage of the await Task.Delay(1000); which leads me to believe that there is an infinite delay, probably because of the await. but as far as I know, logically it should not happen, I also have seen some examples of using await on delay, so it must be possible to do.

2 Answers2

2

By calling clock() from Main you are starting an asynchronous task without waiting for it to complete.

You can make clock() return a Task and use clock().Wait() block Main method until the task is completed (which will never be, because clock() contains an infinite loop and will never end).

Without Wait()ing for the task to complete, the Main will run to completion, causing the application to close.

using System;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Main 1");

        DoSomethingAsync().Wait();

        Console.WriteLine("Main 2");
    }

    public static async Task DoSomethingAsync()
    {
        Console.WriteLine("DoSomethingAsync 1");

        await Task.Delay(1000);

        Console.WriteLine("DoSomethingAsync 2");
    }
}

Output of the application:

Main 1
DoSomethingAsync 1
(delay of 1 second)
DoSomethingAsync 2
Main 2

Without Wait() it would have been:

Main 1
DoSomethingAsync 1
Main 2

or more likely it could have been:

Main 1
Main 2
DoSomethingAsync 1
Fabio Iotti
  • 1,480
  • 1
  • 16
  • 20
1

First and foremost Task.Delay returns a Task. This is necessary because we might need to make the application wait before executing the logic.

And Second, if you want to make only the clock method synchronous then it's not recommended to use make it static. Because it will block the whole class for execution. Please refer this to know more about synchronous static and non-static methods.

Now with respect to the implementation. As we are making the clock() as a synchronous non-static method. We need to create the object of the class in the main method and call the clock().

    Program p = new Program();
    p.clock();

We can use Task.Run() to create a new thread.

    public Task clock()
    {
        while (true)
        {
            Console.WriteLine(DateTime.Now.ToString());
            Task.Run(() => Task.Delay(1000));
            Console.Clear();
        }
    }
  • Static has no impact on async/sync behavior. It doesn't 'block the whole class'. That link you refer to is for Java and its synchronized concept – pinkfloydx33 Aug 25 '19 at 22:28