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

后端 未结 16 2583
后悔当初
后悔当初 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:37

    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)
    {
        ...
    }
    

提交回复
热议问题