Search code examples
c#async-awaittask

Why I can't see the console write when using async await Task?


I'm new in C#. I wrote a code run C# as below and run in main console:

using System;
using System.Threading.Tasks;
class HelloWorld 
{
  static void Main() 
  {
    Task t = example1();
  }
  
  static async Task DoWork()
  {
    Console.WriteLine( " Hello World! " ); 
    for ( int i = 0 ; i < 3 ; i++ ) 
    { 
       Console.WriteLine( " Working..{0} " ,i); 
       await   Task.Delay( 1000 ); 
    } 
  }
  
  static async Task example1()
  {
      await DoWork();
      Console.WriteLine( " First async Run End " ); 
  }
}

I pressed run and get the answer: The console image 1

Could anyone help me understand what's wrong happend in first code? And how to realize the async/await correctly? I have read a lot about async/await C#, but still confuse it. Thanks.

But when I try to add the t.Wait() in Main() like:

using System;
using System.Threading.Tasks;
class HelloWorld 
{
  static void Main() 
  {
    Task t = example1();
    t.Wait();
  }
  
  static async Task DoWork()
  {
    Console.WriteLine( " Hello World! " ); 
    for ( int i = 0 ; i < 3 ; i++ ) 
    { 
       Console.WriteLine( " Working..{0} " ,i); 
       await   Task.Delay( 1000 ); 
    } 
  }
  
  static async Task example1()
  {
      await DoWork();
      Console.WriteLine( " First async Run End " ); 
  }
}

I can get the answer: console image 2

I think I'm not realize the async/await correctly.


Solution

  • You should be using

    static async Task Main() 
    {
        await example1();
    }
    
    

    In your first example your process will exit directly after reaching the first await. And this will prevent anything after any await to run. Making the main method async Task Main() will ensure your process stays alive until the returned task completes.

    I would recommend How async await really works if you want to know more about the internal details of async.