Continuations Are Worth Being Hot
And in some other work I'm doing right now, I desperately wish for continuations in C#. I am attempting to asynchronously decode buffers into message structures, and the painful callback-based approach used by .NET's Begin/End/IAsyncResult approach makes it extraordinarily difficult to code. In order to avoid blocking a thread, I am forced to either stitch together a confusing chain of callbacks, or read data in a larger blocks. The problems with the former are lack of understandability and difficult debugging, and the problem with the latter is that message parsing often requires small chunks to be read to determine how much more is to be read to complete the message.
I yearn to be able to write code like the following, despite my unwieldy made-up syntax and lack of error checking.
Message Decode(Stream stream)
{
BinaryReader reader = new BinaryReader(stream);
Message msg = new Message();
msg.Foo = Continuation.CallWithCurrent(reader.ReadInt32);
msg.Bar = Continuation.CallWithCurrent(reader.ReadInt32);
return msg;
}
Then, the BinaryReader would support something like this:
void ReadInt32(Continuation continuation)
{
// Set in the constructor.
this.stream.BeginRead(this.buffer, 0, 4, delegate(IAsyncResult result)
{
this.stream.EndRead(result);
int result = this.ConvertBufferToInt32();
continuation(result);
});
}
I could write my deserialization function as a nice procedural list of instructions, and not have to worry about blocking a thread while I wait. You could, of course, push the continuation call farther down the stack into the stream or socket or from whatever is being read.

Here's the scenario: I need to collect photo IDs for editing. As a simple solution, I have a very small dialog box that contains a text field, an "Add Another" button, a "Done" button, and a "Cancel" button. When the user clicks "Add Another," I want to save the entered photo ID and re-display the dialog. If they click "Done," the currently entered ID should be saved, and the dialog should vanish. Finally, if they click cancel, the current ID does not get saved, and the dialog disappears.







