Regarding how Async and Await works c#

前端 未结 7 1195
深忆病人
深忆病人 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:20

    Both of the your statements are probably true, but are confusing.

    Async-await does usually complete on a separate background thread but it doesn't mean it starts any separate background thread to complete the job.

    The point of these asynchronous operations is to to not hold a thread while an asynchronous operation is being executed because true asynchronous operations do not require a thread.

    The parts before that operation can be CPU bound and do require a thread and they are executed by the calling thread. The parts after that operation (which is usually called the completion) also require a thread. If there's a SynchronizationContext (like there is in UI or asp.net apps) or TaskScheduler then that part is handled by them. If there isn't any that part is scheduled on the ThreadPool to be executed by an already existing background thread.

    So, in your example Task.Delay creates a Task that completes after 5 seconds. During that delay there's no need for a thread so you can use async-await.

    The flow of your example is this: The main thread starts executing Main, calls TestAsyncAwaitMethods, calls LongRunningMethod, prints the first message, calls Task.Delay, registers the rest of the method as a continuation to execute after the Task.Delay completes, return to Main, print the message and waits synchronously (blocks) on Console.ReadLine.

    After 5 seconds the timer in Task.Delay ends and completes the Task returned from Task.Delay. The continuation is then scheduled on the ThreadPool (since it's a console app) and a ThreadPool thread that was assigned that task prints "End Long Running method...".

    In conclusion, a true asynchronous operation doesn't need a thread to be able to run, but it does need a thread after it has completed which is usually a background thread from the ThreadPool but not necessarily.

提交回复
热议问题