Why Does My Asynchronous Code Run Synchronously When Debugging?

前端 未结 4 2015
野性不改
野性不改 2021-01-11 11:58

I am trying to implement a method called ReadAllLinesAsync using the async feature. I have produced the following code:

private static async Tas         


        
4条回答
  •  孤独总比滥情好
    2021-01-11 12:40

    From Task-based Asynchronous Pattern in Microsoft Download Center :

    For performance reasons, if a task has already completed by the time the task is awaited, control will not be yielded, and the function will instead continue executing.

    And

    In some cases, the amount of work required to complete the operation is less than the amount of work it would take to launch the operation asynchronously (e.g. reading from a stream where the read can be satisfied by data already buffered in memory). In such cases, the operation may complete synchronously, returning a Task that has already been completed.

    So my last answer was incorrect (short-timing asynchronous operation is synchronous for performance reasons).

提交回复
热议问题