Asynchronous Functions
Asynchronous Commands are a useful way to organize asynchronous activities, but they don’t have any way to pass values or control back to a caller. This post contains a simple Asynchronous Function library that lets you do that. In C# you call an Asynchronous Function like:
void CallingMethod(...) { ... do some things ... IAsyncFunction<String> httpGet=new HttpGet(... parameters...); anAsynchronousFunction.Execute(CallbackMethod); } void CallbackMethod(CallbackReturnValue<String> crv) { if (crv.Error!=null) { ... handle Error, which is an Exception ...} String returnValue=crv.Value; ... do something with the return value ... }
We’re using generics so that return values can be passed back in a type safe manner. The type of the return value of the asynchronous function is specified in the type parameter of IAsyncFunction and CallbackReturnValue.
Asynchronous functions catch exceptions and pass them back in in the CallbackReturnValue. This makes it possible to propagate exceptions back to the caller, as in synchronous functions. The code to do this must has to be manually replicated in each asynchronous function, however, the code can be put into a wrapper delegate.
You could do the same thing in Java, but the CallbackMethod would need to be a class that implements an interface rather than a delegate.
Paul Houle on April 18th 2008 in Asynchronous Communications, Dot Net, GWT, Java, Silverlight