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
If you're using C# 7.1 or later, go with the nawfal's answer and just change the return type of your Main method to Task
or Task
. If you are not:
async Task MainAsync
like Johan said..GetAwaiter().GetResult()
to catch the underlying exception like do0g said.CTRL+C
should terminate the process immediately. (Thanks binki!)OperationCancelledException
- return an appropriate error code.The final code looks like:
private static int Main(string[] args)
{
var cts = new CancellationTokenSource();
Console.CancelKeyPress += (s, e) =>
{
e.Cancel = !cts.IsCancellationRequested;
cts.Cancel();
};
try
{
return MainAsync(args, cts.Token).GetAwaiter().GetResult();
}
catch (OperationCanceledException)
{
return 1223; // Cancelled.
}
}
private static async Task MainAsync(string[] args, CancellationToken cancellationToken)
{
// Your code...
return await Task.FromResult(0); // Success.
}