Wednesday, July 4, 2007

More on Closures

In yet another simple and highly illustrative example of why closures matter, here's a blog entry representing asynchronous (non-blocking) network I/O with closures. Note the significant reduction in code needed and elimination of explicit state management.




I've reproduced the author's closure-enabled Python code in C#:




The above code doesn't exactly mirror the original author's intent; we could easily utilize an AsyncCallback to to that. What it does do is clearly illustrate how to anonymous methods are used to create lexical closures. In "DoOperationB", we see that after it returns its local "stage2" keeps a reference to another local, "stage3".



The order of execution will be what we intended: DoOperationB, stage2, stage3; however, all of this happens in a non-blocking manner. We could call DoOperationB several times, and upon each execution a new lexical scope would be created that the respective "stage2" and "stage3" delegates would act upon. Without real-world code it may be difficult to see, but the benefits of this approach include:


  • not having to utilize callbacks, and

  • not having to bookmark/track execution state, and (perhaps most subtly)

  • the entire "operation" is modeled in exactly one named method (DoOperationB).

No comments: