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

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

    You can solve this with this simple construct:

    class Program
    {
        static void Main(string[] args)
        {
            Task.Run(async () =>
            {
                // Do any async anything you need here without worry
            }).GetAwaiter().GetResult();
        }
    }
    

    That will put everything you do out on the ThreadPool where you'd want it (so other Tasks you start/await don't attempt to rejoin a Thread they shouldn't), and wait until everything's done before closing the Console app. No need for special loops or outside libs.

    Edit: Incorporate Andrew's solution for uncaught Exceptions.

提交回复
热议问题