Using Func delegate with Async method

前端 未结 4 465
终归单人心
终归单人心 2020-12-24 10:05

I am trying to use Func with Async Method. And I am getting an error.

Cannot convert async lambda expression to delegate type \'Func

4条回答
  •  被撕碎了的回忆
    2020-12-24 10:56

    The path I usually take is to have the Main method invoke a Run() method that returns a Task, and .Wait() on the Task to complete.

    class Program
    {
        public static async Task CallAsyncMethod()
        {
            Console.WriteLine("Calling Youtube");
            HttpClient client = new HttpClient();
            var response = await client.GetAsync("https://www.youtube.com/watch?v=_OBlgSz8sSM");
            Console.WriteLine("Got Response from youtube");
            return response;
        }
    
        private static async Task Run()
        {
            HttpResponseMessage response = await CallAsyncMethod();
            Console.ReadLine();
        }
    
        static void Main(string[] args)
        {
            Run().Wait();
        }
    }
    

    This allows the rest of your Console app to run with full async/await support. Since there isn't any UI thread in a console app, you don't run the risk of deadlocking with the usage of .Wait().

提交回复
热议问题