Synchronous vs. Asynchronous HTTP requests - ios

I am in the process of converting a JavaScript-based hybrid app to a native iOS app. When I started developing the app with JavaScript, I was disappointed to find out that if you want to make an HTTP request, you have to do it asynchronously. I tried to get around this in various ways, basically:
var done = false;
$.post(url, data, function() { done = true; });
while (!done) {}
//Continue
But I came to find that this is ugly and just plain bad practice, so I got over it and just did it asynchronously.
So when I started with iOS I was excited with the idea that I might be able to do it synchronously, but again I was disappointed to find that the recommended practices are asynchronous, favoring closures or delegates to handle responses.
My question has two parts:
Why is it such common practice in almost every case for HTTP requests to be made asynchronously instead of synchronously?
Is there a way to make synchronous requests in iOS that isn't ugly or problematic?
Essentially, I've always wanted to be able to do something like:
var response = SubmitHTTPPostRequest(url, data)
Is this not really a thing? I never learned this kind of thing in school, so I apologize if this is a rudimentary question. I've just never understood why this is the way it's typically done.

You need to understand the process from sending a request to getting a response. The request will most likely go through some network adapter, to some server, back to the adapter and then back to your CPU. In general there are no cases where there is only one processor involved, in the case I described are 3 but usually there are more. That means synchronisation as doing all the work in one process is impossible since multiple processors are involved. The path to synchronisation (as already mentioned) is for your current thread to wait. I can not agree that will freeze your UI but will freeze your thread (which will freeze the UI if it is the main thread). Still putting the whole process into another thread which will wait for response will produce many other issues and questions such as "should I create a thread for each request", "memory consumption if responses take too long to return?"...
I can understand you want this synchronisation so you can do the operation in a single method but in the end this is exactly what makes an ugly code. Your method then consists of creating the request, getting response, processing response and processing the data received all in one. This might seem a good idea on the beginning but when this method becomes too long you will want to refractor the code into at least 3 methods which by coincidence is exactly what you need to do with asynchronous request. So to answer your second question: Very unlikely, the asynchronous procedure looks much less ugly.
What you should do and is done in most cases is to create some class that handles your requests and responses so from the UI part of your code you only need to do a single call. Lets say you have a table view on which you will display a list of your friend received from some social network. When you first come to this list you would like some activity indicator view to notify the user the data is loading, then send some asynchronous request to get the friends not caring when and if the response will return but when the response is received you simply remove the activity indicator and reload the table view with new data received. Now I hope you can imagine this is a very elegant code and by doing so you enable the user to be able to cancel the request by pressing back.
So the main reason for doing request asynchronous is not to block the threads because that may generate multiple issues or even blocking the main thread which will block the UI and if the main thread is blocked for too long the application will be killed in iOS (watchdog). And the reasons to do synchronisation? Well, in long term I can not think of any, you should always break operations into many methods and use callbacks.

First of all, you should be very clear with synchronous and asynchronous terms.
When Synchronous request sent, caller has to wait for the request to complete the process.
And Asynchronous request don't wait for finish.
As per stack overflow answer , i have read once :
When an HttpHandler is called, a thread pool thread is used to run that request and the same thread is used to process the entire request. If that request calls out to a database or another web service or anything else that can take time, the thread pool thread waits. This means thread pool threads spend time waiting on things when they could be used to process other requests.
In contrast, when an HttpAsyncHandler, a mechanism exists to allow the request to register a callback and return the thread pool thread to the pool before the request is fully processed. The thread pool thread starts doing some processing for the request.At that point, the thread pool thread that was processing the HTTP request is returned to the pool to process another HTTP request.
Your Answers :
1.Because , asynchronous request do not wait for task to complete. send request and while in the same time thread can perform other task without waiting. i use ASIHttpRequest in my ios app.
2.We can send request synchronously but not common this days in practice.

Related

Synchronous API requests with Queue in Swift?

I need to execute synchronous requests on API using Swift. Requests must be queued. Meaning, if one is already in progress and it awaits response it must not be canceled or interrupted by the next synchronous request that enters queue or is already in queue.
Requests must be executed in order as they enter queue (FIFO). Next request must not start until previous is finished/completed in the queue.
Also, every single request in queue must be executed until queue is empty. Synchronous requests can enter queue at any time.
I meant to implement a Synchronous API Client as a singleton which contains its own Queue for queued requests. Requests must not stop/freeze UI. UI has to be responsive on user interaction all the time.
I know it can be done with semaphores but, unless you know what your are doing and you are completely sure how semaphores work, it is not the safest or maybe the best way do it. Otherwise, potential bugs and crashes could appear.
I'm expecting successful execution of every synchronous request that enters queue (by FIFO order, regardless if it returns success or an error as a response) and UI updates immediately after.
So, my question is what is the best way to approach and solve this problem?
Thanks for your help and time.
You can create your own DispatchQueue and put you operations on it as DispatchWorkItems. It is serial per default. Just remember to call your completions on DispatchQueue.main if you plan to update the UI.
John Sundell has a wonderful article about DispatchQueues here:
https://www.swiftbysundell.com/articles/a-deep-dive-into-grand-central-dispatch-in-swift/

Async Controller and questions everywhere

I Have a quick question about async Controller and Actions in ASP.Net MVC 4+ (using the async/await programming model returning a Task ).
What do i risk if all my actions are async even if the underline operations are not IO Bound (for example slow web service or network communication ) and can be CPU Bound. I mean all my actions will be async no matter what code is int it . I Hope i'am clear.
Will be performance problems due to synchronisation context overhead or any other significant overhead for a public website that can have a lot of simultanous users ?
Thank you for your futur answers.
What do i risk if all my actions are async even if the underline operations are not IO Bound (for example slow web service or network communication ) and can be CPU Bound.
This is exactly what you don't want to do.
Consider what happens with a synchronous action: the request comes in, ASP.NET allocates a thread for that request, and that thread executes the action. When the action is complete, that same thread sends the response.
Now consider what happens if you "offload" an action's CPU-bound work to the thread pool (e.g., Task.Run). The request comes in, ASP.NET allocates a thread for that request, and the thread starts executing the action. When the thread hits Task.Run, it allocates another thread from the thread pool to execute the CPU-bound code. Then the asynchronous action method hits the await for that task, so the original thread is returned to the ASP.NET runtime. The other thread then finishes the work and continues on to send the response.
So, you're doing more work for every request if you have an asynchronous action that pushes CPU-bound work to the thread pool. You should never do this on ASP.NET.
I explain this in more detail on my blog.
I don't think you will run into any problems for a simple app since the async workers are running off a pool of threads with a limit number of threads. But what you may run into is a condition where the client HTTP threads are waiting on the asyn response and it exceeds a network gateway timeout. For instance, amazon ELB have a 60 second timeout. So clients can be disconnected while the async task is still running. If that happens a lot then you could end up with a lot of async tasks running and completing with no client to respond to. That would be an unfortunate condition because your clients are not getting data and your server is working for nothing.
One thing I would consider is whether or not you need async calls. I would suggest tuning up your service calls and making sure they are fast enough to address load instead of making the front end async as a workaround for the latency. For instance, using caching. Just a suggestion.
Hope it helps.

Using GCD for offline persistent queue

Right now I have some older code I wrote years ago that allows an iOS app to queue up jobs (sending messages or submitting data to a back-end server, etc...) when the user is offline. When the user comes back online the tasks are run. If the app goes into the background or is terminated the queue is serialized and then loaded back when the app is launched again. I've subclassed NSOperationQueue and my jobs are subclasses of NSOperation. This gives me the flexibility of having a data structure provided for me that I can subclass directly (the operation queue) and by subclassing NSOperation I can easily requeue if my task fails (server is down, etc...).
I will very likely leave this as it is, because if it's not broke don't fix it, right? Also these are very lightweight operations and I don't expect in the current app I'm working on for there to be very many tasks queued at any given time. However I know there is some extra overhead with using NSOperation rather than using GCD directly.
I don't believe I could subclass a dispatch queue the way I can an NSOperationQueue, so there would be extra code overheard for me to maintain my own data structure and load this into & out of a dispatch queue each time the app is sent to the background, right? Also not sure how I'd handle requeueing the job if it fails. Right now if I get a HTTP 500 response from the server, for example, in my operation code I send a notification with a deep copy of the failed NSOperation object. My custom operation queue picks this notification up and adds the task to itself. Not sure how of if I'd be able to do something similar with GCD. I would also need an easy way to cancel all operations or suspend the queue when network connectivity is lost then reactivate when network access is regained.
Just hoping to get some thoughts, opinions and ideas from others who might have done something similar or are more familiar with GCD than I am.
Also worth noting I know there's some new background task support coming in iOS 7 but it will likely be a while before that will be my deployment target. I am also not sure yet if it would exactly do what I need, so at the moment just looking at the possibility of GCD.
Thanks.
If NSOperation vs submitting blocks to GCD ever shows up as measurable overhead, the problem isn't that you're using NSOperation, it's that your operations are far too granular. I would expect this overhead to be effectively unmeasurable in any real-world situation. (Sure, you could contrive a test harness to measure the overhead, but only by making operations that did effectively nothing.)
Use the highest level of abstraction that gets the job done. Move down only when hard data tells you that you should.

NSURLConnection synchronous request from a thread vs asynchronous request

What is the differance between adding a operation which make a synchronous NSURLConnection request in NSOperationQueue ( or synchronous request from a thread ( not main thread)) AND making a asynchronous request from the main thread ?
Both will not block main thread so UI will remain responsive but is there any advantage of using one over other? I know in later method i can track request progress etc but assume that progress and other HTTP stuff is not important here.
They are very similar. The biggest problem with synchronous requests is that they can't easily be cancelled. Depending on your application, that could be a problem. Imagine you are downloading a big document and the user moves to another screen so you no longer need that information. In our case, I actually chose doing asynchronous NSURLConnections on a secondary NSThread, which may be overkill for some apps. It is more complicated, but it gives us the ability to both cancel requests and to decode the JSON/XML/image data on secondary threads so they don't impact main thread user interactivity.
Asynchronous requests are scheduled on the run loop and setup as a run loop source, triggering the code automatically only when there is data received from the network (as any socket source).
Synchronous requests running on a NSThread monopolizes a thread to monitor the incoming data, which is in general quite overkill.
You can always cancel an NSURLConnection even if it has been executed asynchronously, using the cancel method.
I bet using the new API that allows to send an asynchronous request on an NSOperationQueue (+sendAsynchronousRequest:queue:completionHandler:) uses GCD under the hood and dispatch_source_create, or something similar, so that it behave the same way as when an NSURLConnection is scheduled on the run loop, avoiding using an additional thread (watch the WWDC'12 videos that explains why threads are evil and their usage should be minimized), the difference only being that allows you to use a block to be informed upon completion instead of using the delegate mechanism.
Some years ago I created a class that embedded NSURLConnection asynchronous calls and delegate management into a nice block API (see OHURLLoader on my github) that makes it easier to use (feel free to take a look). I bet the new API that uses NSOperationQueues uses the same principle, still doing asynchronous requests on the runloop but allowing you to use blocks instead of having to implement a delegate.
The historical position was that there's an advantage in power consumption, and therefore battery life, in asynchronous requests — presumably including both the older delegate approach and the new block-based approach.

Synchonous Vs Asynchronous Calling in iOS App

At Apple's site, they say:
"Because this call can potentially take several minutes to fail (particularly when using a cellular network in iOS), you should never call this function from the main thread of a GUI application."
In my case, the Application has nothing (literally nothing), to do in between the calling of WebService and the response returned. (There is no other activity My Application can Perform in between as per Specifications).
What should I do?
Is there any reason, (as per the situation) that can convince -- I should go for Asynchronous Call to WebService.
Any suggestions, as I am not very familiar to it ???
You should always go for asynchronous calls - otherwise you freeze whole UI of your app, due to blocking the main thread.
In other words: user will have his phone blocked when the request will be processed.

Resources