I am new to asynchronous programming with the async
modifier. I am trying to figure out how to make sure that my Main
method of a console applicati
In C# 7.1 you will be able to do a proper async Main. The appropriate signatures for Main
method has been extended to:
public static Task Main();
public static Task<int> Main();
public static Task Main(string[] args);
public static Task<int> Main(string[] args);
For e.g. you could be doing:
static async Task Main(string[] args)
{
Bootstrapper bs = new Bootstrapper();
var list = await bs.GetList();
}
At compile time, the async entry point method will be translated to call GetAwaitor().GetResult()
.
Details: https://blogs.msdn.microsoft.com/mazhou/2017/05/30/c-7-series-part-2-async-main
EDIT:
To enable C# 7.1 language features, you need to right-click on the project and click "Properties" then go to the "Build" tab. There, click the advanced button at the bottom:
From the language version drop-down menu, select "7.1" (or any higher value):
The default is "latest major version" which would evaluate (at the time of this writing) to C# 7.0, which does not support async main in console apps.
I'll add an important feature that all of the other answers have overlooked: cancellation.
One of the big things in TPL is cancellation support, and console apps have a method of cancellation built in (CTRL+C). It's very simple to bind them together. This is how I structure all of my async console apps:
static void Main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
System.Console.CancelKeyPress += (s, e) =>
{
e.Cancel = true;
cts.Cancel();
};
MainAsync(args, cts.Token).GetAwaiter.GetResult();
}
static async Task MainAsync(string[] args, CancellationToken token)
{
...
}
C# 7.1 (using vs 2017 update 3) introduces async main
You can write:
static async Task Main(string[] args)
{
await ...
}
For more details C# 7 Series, Part 2: Async Main
Update:
You may get a compilation error:
Program does not contain a static 'Main' method suitable for an entry point
This error is due to that vs2017.3 is configured by default as c#7.0 not c#7.1.
You should explicitly modify the setting of your project to set c#7.1 features.
You can set c#7.1 by two methods:
Method 1: Using the project settings window:
Method2: Modify PropertyGroup of .csproj manually
Add this property:
<LangVersion>7.1</LangVersion>
example:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
<LangVersion>7.1</LangVersion>
</PropertyGroup>
Newest version of C# - C# 7.1 allows to create async console app. To enable C# 7.1 in project, you have to upgrade your VS to at least 15.3, and change C# version to C# 7.1
or C# latest minor version
. To do this, go to Project properties -> Build -> Advanced -> Language version.
After this, following code will work:
internal class Program
{
public static async Task Main(string[] args)
{
(...)
}
In my case I had a list of jobs that I wanted to run in async from my main method, have been using this in production for quite sometime and works fine.
static void Main(string[] args)
{
Task.Run(async () => { await Task.WhenAll(jobslist.Select(nl => RunMulti(nl))); }).GetAwaiter().GetResult();
}
private static async Task RunMulti(List<string> joblist)
{
await ...
}
class Program
{
public static EventHandler AsyncHandler;
static void Main(string[] args)
{
AsyncHandler+= async (sender, eventArgs) => { await AsyncMain(); };
AsyncHandler?.Invoke(null, null);
}
private async Task AsyncMain()
{
//Your Async Code
}
}