<T> action against standard return

I am not a guy in C # I am more a guy of Objective-C, but lately I have seen many implementations:

public void Method(Action<ReturnType> callback, params...) 

Instead:

 public ReturnType Method(params...) 

One example of this is the MVVM Light Framework, where a developer implements a data service contract (and implementation) using the first approach, so my question is: why is this? This is just a matter of sympathy or the first asynchronous defaut approach (given the function pointer). If true, is this the standard return death? I ask why I personally like that the second approach is clearer for me when I see the API.

+6
source share
2 answers

Unlike the ReturnType API ReturnType , the version with the callback can immediately return and execute the callback later. This can be important when the return value is not immediately available, and receiving it entails a significant delay. For example, an API that requests data from a web service can take considerable time. If no continuation is required to get the results, you can initiate a call and provide an asynchronous callback. In this way, the caller will be able to continue working and process the notifications when they become available.

Consider an API that takes an image URL and returns a representation of the image in memory. If your API

 Image GetImage(URL url) 

and your users need to pull out ten images, they will either have to wait until each image finishes loading before requesting the next one, or it will start several streams explicitly.

On the other hand, if your API

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

then your API users will initiate all ten requests at the same time and display the images when they become available asynchronously. This approach greatly simplifies the thread programming that users must perform.

+10
source

The first method is likely to be an asynchronous method when the method returns immediately and the callback is called after the operation completes.

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

Of course, API developers can make any signature that seems to be appropriate; and there may be other basic details to justify the callback style. But usually, if you see a callback style, expect the method to be asynchronous.

+3
source

Source: https://habr.com/ru/post/917686/


All Articles