I’m not a C# guy I’m more an Objective-C guy but lately I’ve seen a lot of implementations of:
public void Method(Action<ReturnType> callback, params...)
Instead of:
public ReturnType Method(params...)
One of the examples of this is the MVVM Light Framework, there the developer implements the data service contract (and implementation) using the first approach, so my question is: Why this? Is just a matter of likes or is the first approach asyncronous by defaut (given the function pointer). If that’s true, is the standard return death? I ask cause I personally like the second approach is more clear to me when I see an API.
Unlike the API returning
ReturnType, a version with callback can return right away, and perform the callback later. This may be important when the value to return is not immediately available, and getting it entails a considerable delay. For example, and API that requests the data from a web service may take considerable time. When the result data is not required to proceed, you could initiate a call, and provide an asynchronous callback. This way the caller would be able to proceed right away, and process notifications when they become available.Consider an API that takes a URL of an image, and returns an in-memory representation of the image. If your API is
and your users need to pull ten images, they would either need to wait for each image to finish loading before requesting the next one, or start multiple threads explicitly.
On the other hand, if your API is
then the users of your API would initiate all ten requests at the same time, and display the images as they become available asynchronously. This approach greatly simplifies the thread programming the users are required to do.