What's the relationship between the async/await pattern and continuations?
Asked Answered
S

1

9

I'm wondering what's the relationship between the async/await pattern (as known from Scala, F#, C#, etc.) and continuations:

  • Is the async/await pattern a limited subset of full-blown continuations? (If true, how are continuations more expressive?)
  • Are continuations just one possible implementation technique for async/await? (If true, what other implementation approaches exist?)
  • Or are async/await and continuations just orthogonal concepts where the only commonality is that they both enable some abstraction of control flow/data flow?
Shorthand answered 2/4, 2014 at 16:33 Comment(1)
L
5

I would say that the relation between the two is this: async-await is a technique programming languages use so that you can write code that looks synchronous (e.g. no explicit continuation delegates), but that is actually executed asynchronously. This is achieved by creating an object that represents the current state of execution of the function and registering that as the continuation of the awaited operation.

In short, async-await uses continuations.

Is the async/await pattern a limited subset of full-blown continuations? (If true, how are continuations more expressive?)

You could say that. Continuations are a more general concept, async-await just uses them to achieve asynchrony.

For example, in continuation-passing style programming, you could implement exception handling by having two continuations for each operation: one for the success case and one for the failure case. This use of continuations has nothing to do with async-await (you would have to write each continuation explicitly, probably as a lambda).

Are continuations just one possible implementation technique for async/await? (If true, what other implementation approaches exist?)

I'd say that the concept of continuation is pretty central to async-await.

The core idea being async-await is to stop executing the function for now and resume it at a later time. And for that, you need some kind of object that can be used to do that resuming. Which is exactly what a continuation is.

Ludlow answered 3/4, 2014 at 11:58 Comment(5)
Also, ContinueWith enables resuming an async method. This would not be possible with raw threads, for example, because you can't get called back when it exits. You can only wait.Karakorum
Although, continuation is not necessarily about asynchronous execution. One other example is yield which original purpose has nothing to do with asynchrony.Nickelson
@Noseratio Yeah, that's part of what I've been trying to say.Ludlow
@svick. Thanks for your answer! Could you comment on how async/await uses continuations? (E. g. is it just hooking into shift/reset underneath or is there more magic happening?)Shorthand
@Shorthand I think async-await has nothing to do with delimited continuations, it just uses normal continuations.Ludlow

© 2022 - 2024 — McMap. All rights reserved.