C# 5's async
and await
made asynchronous programming much simpler than before with the elimination of callbacks and method chains.
One omission however was the lack of support for Program.Main()
to be async thus forcing console programs to be a little more convoluted in order to be able to use the many async operations now available in the .NET Framework.
C# 7.1 solves this by allowing Program.Main()
to be async just like any other method with the compiler taking care of any necessary work behind the scenes.
Code
C#
class Program
{
static async Task<int> Main(string[] args)
{
try
{
const text = await File.ReadAllTextAsync(args[1]);
Console.WriteLine(text);
}
catch(Exception ex)
{
Console.Error.WriteLine(ex);
return -1;
}
}
}
C#
class Program
{
static int Main(string[] args)
{
try
{
return AsyncContext.Run(() => {
const text = await File.ReadAllTextAsync(args[1]);
Console.WriteLine(text);
});
}
catch(Exception ex)
{
Console.Error.WriteLine(ex);
return -1;
}
}
}
Notes
- The C# 7.1+ compiler builds a state machine using AsyncTaskMethodBuilder behind the scenes