Saturday, June 03, 2006

Closure and asynchronous functions

Closures are, in a programming langage, the ability to access at runtime in a local function the objects available at runtime at the point of definition of that local function. For instance void somefunction () { string variable1 = "Hello"; myButton.Click += delegate { myButton.Text = variable1;} } will be legal, even though the button will be clicked way after somefunction() has exited, where the variable variable1 is normally out of scope. This are very handy when dealing with asynchronous programming. Asynchronous programming involves breaking down a single function into a call to a service, and a treatment of the response to that service. Closures enable you to access to a single set of variables, just like in a single function, across all the pieces from the original function. void synchronousfunction() { myquerybutton.status = disabled; results = makebigQuery(); window.display(variable); myquerybutton.status = enabled; } void asynchronousfunction() { myquerybutton.status = disabled; query.oncomplete += new function(results) { window.display(results); myquerybutton.status = enabled; } query.launchquery(); } The code looks very much alike, thanks to the closure. These kind of closure can be found in csharp, javascript 1.5 and many functional programming langages. Now if someone knows an easy way to synchronize my job schedule with my personal one, I'd be glad :)

1 Comments:

At 10:00 AM, Blogger zproxy said...

in c# delegates are actually just anonymous types with methods and properties.

the local variable can be converted into type member at compile time.

have a look at my project at
my blog.

The project specializeds in converting a c# assambly to javascript (and php and java :)

 

Post a Comment

Links to this post:

Create a Link

<< Home