Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action<T> vs Standard Return

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.

like image 213
Erre Efe Avatar asked Jun 09 '12 14:06

Erre Efe


2 Answers

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

Image GetImage(URL url)

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

void Method(Action<Image> callback, URL url)

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.

like image 179
Sergey Kalinichenko Avatar answered Sep 22 '22 02:09

Sergey Kalinichenko


The first method is likely to be an asynchronous method, where the method returns immediately and the callback is called once the operation has finished.

The second method is the standard way of doing method returns for (synchronous) methods in C#.

Of course, API designers are free to make whatever signature they seem fit; and there might be other underlying details to justify the callback style. But, as a rule of thumb, if you see the callback style, expect the method to be asynchronus.

like image 32
driis Avatar answered Sep 22 '22 02:09

driis