<p>What are they and what are they good for?</p>

<p>I do not have a CS degree and my background is VB6 -> ASP -> ASP.NET/C#. Can anyone explain it in a clear and concise manner?</p>

[{'answer_id': 40643, 'author': 'John Millikin', 'author_id': 3560, 'author_profile': 'https://Stackoverflow.com/users/3560', 'pm_score': 6, 'selected': True, 'text': '<p>Imagine if every single line in your program was a separate function. Each accepts, as a parameter, the next line/function to execute. </p>\n\n<p>Using this model, you can "pause" execution at any line and continue it later. You can also do inventive things like temporarily hop up the execution stack to retrieve a value, or save the current execution state to a database to retrieve later.</p>\n'}, {'answer_id': 40736, 'author': 'Kyle Cronin', 'author_id': 658, 'author_profile': 'https://Stackoverflow.com/users/658', 'pm_score': 3, 'selected': False, 'text': '<p>A heads up, this example is not concise nor exceptionally clear. This is a demonstration of a powerful application of continuations. As a VB/ASP/C# programmer, you may not be familiar with the concept of a system stack or saving state, so the goal of this answer is a demonstration and not an explanation.</p>\n\n<p>Continuations are extremely versatile and are a way to save execution state and resume it later. Here is a small example of a cooperative multithreading environment using continuations in Scheme:</p>\n\n<p>(Assume that the operations enqueue and dequeue work as expected on a global queue not defined here)</p>\n\n<pre><code>(define (fork)\n  (display "forking\\n")\n  (call-with-current-continuation\n   (lambda (cc)\n     (enqueue (lambda ()\n                (cc #f)))\n     (cc #t))))\n\n(define (context-switch)\n  (display "context switching\\n")\n  (call-with-current-continuation\n   (lambda (cc)\n     (enqueue\n      (lambda ()\n        (cc \'nothing)))\n     ((dequeue)))))\n\n(define (end-process)\n  (display "ending process\\n")\n  (let ((proc (dequeue)))\n    (if (eq? proc \'queue-empty)\n        (display "all processes terminated\\n")\n        (proc))))\n</code></pre>\n\n<p>This provides three verbs that a function can use - fork, context-switch, and end-process. The fork operation forks the thread and returns #t in one instance and #f in another. The context-switch operation switches between threads, and end-process terminates a thread.</p>\n\n<p>Here\'s an example of their use:</p>\n\n<pre><code>(define (test-cs)\n  (display "entering test\\n")\n  (cond\n    ((fork) (cond\n              ((fork) (display "process 1\\n")\n                      (context-switch)\n                      (display "process 1 again\\n"))\n              (else (display "process 2\\n")\n                    (end-process)\n                    (display "you shouldn\'t see this (2)"))))\n    (else (cond ((fork) (display "process 3\\n")\n                        (display "process 3 again\\n")\n                        (context-switch))\n                (else (display "process 4\\n")))))\n  (context-switch)\n  (display "ending process\\n")\n  (end-process)\n  (display "process ended (should only see this once)\\n"))\n</code></pre>\n\n<p>The output should be</p>\n\n<pre><code>entering test\nforking\nforking\nprocess 1\ncontext switching\nforking\nprocess 3\nprocess 3 again\ncontext switching\nprocess 2\nending process\nprocess 1 again\ncontext switching\nprocess 4\ncontext switching\ncontext switching\nending process\nending process\nending process\nending process\nending process\nending process\nall processes terminated\nprocess ended (should only see this once)\n</code></pre>\n\n<p>Those that have studied forking and threading in a class are often given examples similar to this. The purpose of this post is to demonstrate that with continuations you can achieve similar results within a single thread by saving and restoring its state - its continuation - manually.</p>\n\n<p>P.S. - I think I remember something similar to this in On Lisp, so if you\'d like to see professional code you should check the book out.</p>\n'}, {'answer_id': 40749, 'author': 'Jason Baker', 'author_id': 2147, 'author_profile': 'https://Stackoverflow.com/users/2147', 'pm_score': 2, 'selected': False, 'text': '<p>Basically, a continuation is the ability for a function to stop execution and then pick back up where it left off at a later point in time.  In C#, you can do this using the yield keyword.  I can go into more detail if you wish, but you wanted a concise explanation.  ;-)</p>\n'}, {'answer_id': 389897, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>I\'m still getting "used" to continuations, but one way to think about them that I find useful is as abstractions of the Program Counter (PC) concept.  A PC "points" to the next instruction to execute in memory, but of course that instruction (and pretty much every instruction) points, implicitly or explicitly, to the instruction that follows, as well as to whatever instructions should service interrupts.  (Even a NOOP instruction implicitly does a JUMP to the next instruction in memory.  But if an interrupt occurs, that\'ll usually involve a JUMP to some other instruction in memory.)</p>\n\n<p>Each potentially "live" point in a program in memory to which control might jump at any given point is, in a sense, an active continuation.  Other points that can be reached are potentially active continuations, but, more to the point, they are continuations that are potentially "calculated" (dynamically, perhaps) as a result of reaching one or more of the currently active continuations.</p>\n\n<p>This seems a bit out of place in traditional introductions to continuations, in which all pending threads of execution are explicitly represented as continuations into static code; but it takes into account the fact that, on general-purpose computers, the PC points to an instruction sequence that might potentially change the contents of memory representing a portion of that instruction sequence, thus essentially creating a new (or modified, if you will) continuation on the fly, one that doesn\'t really exist as of the activations of continuations preceding that creation/modification.</p>\n\n<p>So continuation can be viewed as a high-level model of the PC, which is why it conceptually subsumes ordinary procedure call/return (just as ancient iron did procedure call/return via low-level JUMP, aka GOTO, instructions plus recording of the PC on call and restoring of it on return) as well as exceptions, threads, coroutines, etc.</p>\n\n<p>So just as the PC points to computations to happen in "the future", a continuation does the same thing, but at a higher, more-abstract level.  The PC implicitly refers to memory plus all the memory locations and registers "bound" to whatever values, while a continuation represents the future via the language-appropriate abstractions.</p>\n\n<p>Of course, while there might typically be just one PC per computer (core processor), there are in fact many "active" PC-ish entities, as alluded to above.  The interrupt vector contains a bunch, the stack a bunch more, certain registers might contain some, etc.  They are "activated" when their values are loaded into the hardware PC, but continuations are abstractions of the concept, not PCs or their precise equivalent (there\'s no inherent concept of a "master" continuation, though we often think and code in those terms to keep things fairly simple).</p>\n\n<p>In essence, a continuation is a representation of "what to do next when invoked", and, as such, can be (and, in some languages and in continuation-passing-style programs, often is) a first-class object that is instantiated, passed around, and discarded just like most any other data type, and much like how a classic computer treats memory locations <em>vis-a-vis</em> the PC -- as nearly interchangeable with ordinary integers.</p>\n'}, {'answer_id': 389940, 'author': 'Dustin', 'author_id': 39975, 'author_profile': 'https://Stackoverflow.com/users/39975', 'pm_score': 4, 'selected': False, 'text': '<p>You probably understand them better than you think you did.</p>\n\n<p>Exceptions are an example of "upward-only" continuations.  They allow code deep down the stack to call up to an exception handler to indicate a problem.</p>\n\n<p>Python example:</p>\n\n<pre><code>try:\n    broken_function()\nexcept SomeException:\n    # jump to here\n    pass\n\ndef broken_function():\n    raise SomeException() # go back up the stack\n    # stuff that won\'t be evaluated\n</code></pre>\n\n<p>Generators are examples of "downward-only" continuations.  They allow code to reenter a loop, for example, to create new values.</p>\n\n<p>Python example:</p>\n\n<pre><code>def sequence_generator(i=1):\n    while True:\n        yield i  # "return" this value, and come back here for the next\n        i = i + 1\n\ng = sequence_generator()\nwhile True:\n    print g.next()\n</code></pre>\n\n<p>In both cases, these had to be added to the language specifically whereas in a language with continuations, the programmer can create these things where they\'re not available.</p>\n'}, {'answer_id': 396305, 'author': 'Paul Johnson', 'author_id': 49220, 'author_profile': 'https://Stackoverflow.com/users/49220', 'pm_score': 3, 'selected': False, 'text': '<p>One way to think of a continuation is as a processor stack.  When you "call-with-current-continuation c" it calls your function "c", and the parameter passed to "c" is your current stack with all your automatic variables on it (represented as yet another function, call it "k").  Meanwhile the processor starts off creating a new stack.  When you call "k" it executes a "return from subroutine" (RTS) instruction on the original stack, jumping you back in to the context of the original "call-with-current-continuation" ("call-cc" from now on) and allowing your program to continue as before.  If you passed a parameter to "k" then this becomes the return value of the "call-cc".</p>\n\n<p>From the point of view of your original stack, the "call-cc" looks like a normal function call.  From the point of view of "c", your original stack looks like a function that never returns.</p>\n\n<p>There is an old joke about a mathematician who captured a lion in a cage by climbing into the cage, locking it, and declaring himself to be outside the cage while everything else (including the lion) was inside it.  Continuations are a bit like the cage, and "c" is a bit like the mathematician.  Your main program thinks that "c" is inside it, while "c" believes that your main program is inside "k".</p>\n\n<p>You can create arbitrary flow-of-control structures using continuations.  For instance you can create a threading library.  "yield" uses "call-cc" to put the current continuation on a queue and then jumps in to the one on the head of the queue.  A semaphore also has its own queue of suspended continuations, and a thread is rescheduled by taking it off the semaphore queue and putting it on to the main queue.</p>\n'}, {'answer_id': 396691, 'author': 'Rich Dougherty', 'author_id': 49630, 'author_profile': 'https://Stackoverflow.com/users/49630', 'pm_score': 2, 'selected': False, 'text': "<p>In C#, you have access to two continuations. One, accessed through <code>return</code>, lets a method continue from where it was called. The other, accessed through <code>throw</code>, lets a method continue at the nearest matching <code>catch</code>.</p>\n\n<p>Some languages let you treat these statements as first-class values, so you can assign them and pass them around in variables. What this means is that you can stash the value of <code>return</code> or of <code>throw</code> and call them later when you're <em>really</em> ready to return or throw.</p>\n\n<pre><code>Continuation callback = return;\ncallMeLater(callback);\n</code></pre>\n\n<p>This can be handy in lots of situations. One example is like the one above, where you want to pause the work you're doing and resume it later when something happens (like getting a web request, or something).</p>\n\n<p>I'm using them in a couple of projects I'm working on. In one, I'm using them so I can suspend the program while I'm waiting for IO over the network, then resume it later. In the other, I'm writing a programming language where I give the user access to continuations-as-values so they can write <code>return</code> and <code>throw</code> for themselves - or any other control flow, like <code>while</code> loops - without me needing to do it for them.</p>\n"}, {'answer_id': 396721, 'author': 'Jules', 'author_id': 40078, 'author_profile': 'https://Stackoverflow.com/users/40078', 'pm_score': 1, 'selected': False, 'text': '<p>Think of threads. A thread can be run, and you can get the result of its computation. A continuation is a thread that you can copy, so you can run the same computation twice.</p>\n'}, {'answer_id': 397213, 'author': 'ja.', 'author_id': 15467, 'author_profile': 'https://Stackoverflow.com/users/15467', 'pm_score': 1, 'selected': False, 'text': '<p>Continuations have had renewed interest with web programming because they nicely mirror the pause/resume character of web requests.  A server can construct a continaution representing a users session and resume if and when the user continues the session.</p>\n'}]
['https://Stackoverflow.com/questions/40632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1583/']