Recursion and the await / async Keywords

后端 未结 2 864
情话喂你
情话喂你 2020-12-29 03:18

I have a fragile grasp of how the await keyword works, and I want to extend my understanding of it a bit.

The issue that still makes my head spin is the

2条回答
  •  伪装坚强ぢ
    2020-12-29 03:37

    The part up to the first await in any function runs synchronously. In the first case it runs into a stack overflow because of that - there is nothing interrupting the function calling itself.

    The first await (which does not complete immediately - this is the case for you with high likelyhood) causes the function to return (and to give up its stack space!). It queues the rest of it as a continuation. The TPL ensures that continuations never nest too deeply. If there is a risk of stack overflow the continuation is queued to the thread pool, resetting the stack (which was starting to fill up).

    The second example can still overflow! What if the Task.Run task always completed immediately? (This is unlikely but possible with the right OS thread scheduling). Then, the async function would never be interrupted (causing it to return and free all stack space) and the same behavior as in case 1 would result.

提交回复
热议问题