Recursion and the await / async Keywords

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)