Regarding how Async and Await works c#

前端 未结 7 1287
深忆病人
深忆病人 2021-01-13 12:40

i saw some post regarding Async and Await usage in this site. few people are saying that Async and Await complete its job on separate background thread means spawn a new bac

7条回答
  •  盖世英雄少女心
    2021-01-13 13:07

    Need understand two things: a) async/await use tasks(tasks use thread pool) b) async/await is NOT for parallel work.

    Just compile this and look at Id's:

    static void Main(string[] args)
        {
            Console.WriteLine("Id main thread is: {0}", Thread.CurrentThread.ManagedThreadId);
            TestAsyncAwaitMethods();
            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
    
        public async static void TestAsyncAwaitMethods()
        {
            Console.WriteLine("Id thread (void - 0) is: {0}", Thread.CurrentThread.ManagedThreadId);
            var _value = await LongRunningMethod();
            Console.WriteLine("Id thread (void - 1) is: {0}", Thread.CurrentThread.ManagedThreadId);
        }
    
        public static async Task LongRunningMethod()
        {
            Console.WriteLine("Id thread (int) is: {0}", Thread.CurrentThread.ManagedThreadId);
            Console.WriteLine("Starting Long Running method...");
            await Task.Delay(1000);
            Console.WriteLine("End Long Running method...");
            return 1;
        }
    

提交回复
热议问题