Async Main in C#

Async Main in C# with Examples

In this article, I am going to discuss the Async Main in C# with Examples. Please read our previous article where we discussed the Thrown Expression in C# with some examples. From C# 7.1 now it is possible to define the Main method as Async. At the end of this article, you will understand what exactly Async Main is in C# and when and how to use Async Main with examples.

There are two types of programs that the C# language compiler can build. One is a program with an entry point so that the Operating System can load the program and execute it from the entry point. The other is the program without an entry point. Operating System cannot directly execute such types of programs. Such type of programs needs to be referenced by other programs which have an entry point.

The Application which must have an entry point includes Windows Forms App, Console App, WPF App, ASP.NET and ASP.NET Core App, and Xamarian App. On the other hand, the Applications which do not have an entry point include the Class Library.

Activating C# 7.1 features

To make Visual Studio 2017 use some other versions of C# follow the steps shown in the below image.

Async Main in C#

For those who need some more help the steps are described here:

  1. Right-click on the project name and select Properties from the context menu
  2. Select the Build tab from left
  3. Scroll down and click the Advanced button to open advanced build settings
  4. From the Language version drop-down select the C# version you are interested in

C# latest minor version (latest) is the option to select if you want the latest version of C#.

The Main Method in C#

Like other programming languages, the C# program also starts from the Main method with the following properties. 

  1. The C# entry point method must be static,
  2. The name of the method must be Main
  3. The return type of this method can be either void or int.
  4. It can have one parameter of a string array, containing any command-line arguments.

There are four overloaded versions that are considered as the valid signatures for the Main method in C# as shown below.

public static void Main();
public static int Main();
public static void Main(string[] args);
public static int Main(string[] args);

Before C# 7.1, when we wanted to call the async method from within the Main() method, then we need to add some code but now, C# compiler does it for us. Let’s try to understand how to call the async method from Main in C# before C# 7.1 with an example as shown below.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Before C# 7.1, To use async method");
        Console.WriteLine($"Main Method execution started at {System.DateTime.Now}");
        Task.Delay(2000).GetAwaiter().GetResult();
        Console.WriteLine($"Main Method execution ended at {System.DateTime.Now}");

        Console.WriteLine("Press any key to exist.");
        Console.ReadKey();
    }
}
Output:

Why we need Async Main in C#?

Async Main in C#:

From C# 7.1, the Main() method which is the entry point of the application can be declared as async. Before C# 7.1, the Main() method can have a return type as either void or int; however, now, it also supports Task and Task<int>. So From C# 7.1, now we have eight overload versions that are considered as the valid signatures for the Main() method as shown below.

public static void Main();
public static int Main();
public static void Main(string[] args);
public static int Main(string[] args);
public static Task Main();
public static Task<int> Main();
public static Task Main(string[] args);
public static Task<int> Main(string[] args);
Let us understand async main in C# with an example as shown below.
class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("In C# 7.1, To use async method");
        Console.WriteLine($"Main Method execution started at {System.DateTime.Now}");
        await Task.Delay(2000);
        Console.WriteLine($"Main Method execution ended at {System.DateTime.Now}");

        Console.WriteLine("Press any key to exist.");
        Console.ReadKey();
    }
}
Output:

Async Main in C#

As you can see in the above example, the Task.Delay is adding 2 seconds delay in the program execution. Now, C# 7.1 syntax is simpler and easy to use. In the above example, we see how we could use the Task with Main. Now, let’s take another example where we will see the use of Task<int>.

Here, we will call another async method AdditionAsync from Main.

class Program
{
    public static async Task<int> Main(string[] args)
    {
        Console.Title = "async Task<int> Main";
        int number1 = 5, number2 = 10;
        Console.WriteLine($"Sum of {number1} and {number2} is: {await AdditionAsync(number1, number2)}");

        Console.WriteLine("Press any key to exist.");
        Console.ReadKey();

        return 0;
    }

    private static Task<int> AdditionAsync(int no1, int no2)
    {
        return Task.Run(() => SUM(no1, no2));

        //Local function 
        int SUM(int x, int y)
        {
            return x + y;
        }
    }
}
Output:

Async Main in C#

You can also see that in the above example, we have used a Local function SUM that is one of the new features of C# 7.0. 

In the next article, I am going to discuss Exception Handling in C# with real-time examples. Here, in this article, I try to explain Async Main in C# step by step with some simple examples. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

2 thoughts on “Async Main in C#”

  1. blank

    In the last section of this article, you have written AdditionAsync(int no1, int no2) using Task, I think since it’s is an immediately available operation, should it be written ValueTask as below

    private static ValueTask AdditionAsync(int no1, int no2)
    {
    return Task.Run(() => SUM(no1, no2));
    //Local function
    int SUM(int x, int y)
    {
    return x + y;
    }
    }

    Please suggest. Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *