Can't specify the 'async' modifier on the 'Main' method of a console app

后端 未结 16 2016
后悔当初
后悔当初 2020-11-21 07:44

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

16条回答
  •  终归单人心
    2020-11-21 08:30

    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:

    • Have an async Task MainAsync like Johan said.
    • Call its .GetAwaiter().GetResult() to catch the underlying exception like do0g said.
    • Support cancellation like Cory said.
    • A second CTRL+C should terminate the process immediately. (Thanks binki!)
    • Handle 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.
    }
    

提交回复
热议问题