Does all NSURLConnections connect asynchronously? iOs - asynchronous

I've looked through some NSURLConnection examples, and all are titled as related asynchronously, although I didn't see any operation queue / thread/ dispatch created.
I was wondeirng - does NSURLConnection always preform requests asynchronously or you have to set something special for it?

NSURLConnection can be run in synchronous or asynchronous mode depending on what method you call to make the actual connection once you've allocated the NSURLConnection Instance (or use the Class Methods).
For synchronous Connections, you use the method:
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
For asynchronous connections, you use the methods:
+ (NSURLConnection *)connectionWithRequest:(NSURLRequest *)request delegate:(id < NSURLConnectionDelegate >)delegate
- (id)initWithRequest:(NSURLRequest *)request delegate:(id < NSURLConnectionDelegate >)delegate
- (id)initWithRequest:(NSURLRequest *)request delegate:(id < NSURLConnectionDelegate >)delegate startImmediately:(BOOL)startImmediately
- (void)start
I recommend reading Apple's Documentation on NSURLConnection to find out more information and looking at sample code

Related

What is the difference between call_cq and notification_cq in gRPC?

https://github.com/grpc/grpc/blob/master/examples/cpp/helloworld/greeter_async_server.cc#L91
service_->RequestSayHello(&ctx_, &request_, &responder_, cq_, cq_,
this);
The two occurrences of cq_ look strange to me so I dig into the source code which leads me to
https://github.com/grpc/grpc/blob/master/include/grpcpp/impl/codegen/service_type.h#L92
void RequestAsyncUnary(int index, ServerContext* context, Message* request,
internal::ServerAsyncStreamingInterface* stream,
CompletionQueue* call_cq,
ServerCompletionQueue* notification_cq, void* tag) {
server_->RequestAsyncCall(methods_[index].get(), context, stream, call_cq,
notification_cq, tag, request);
}
So what's the difference between call_cq and notification_cq? What are the potential uses/benefits for using difference completion queues?
Here's a quote from the google-groups forum for grpc when this same question was asked.
https://groups.google.com/forum/#!topic/grpc-io/V4NAQ77PMEo
Notification_cq gets the tag back indicating a call has started. All subsequent operations (reads, writes, etc) on that call report back to call_cq. For most async servers my recommendation is to use the same cq. Places where you might not:
Our sync API creates a cq per call under the covers... So it posts a general event >queue for notification_cq, and it's specific queue as call_cq.
If you want to be able to control when you accept incoming calls vs when you don't (by suspending polling on a notification_cq)
I'm sure folks can think of others.
This allows fine-grained control over which threads handle which kinds of events (based on which queues they are polling). Like you may have a master thread polling the notification_cq and worker threads all polling their own call_cqs, or something like that.

Async ZeroMQ for nim

I have never used ZeroMQ and first heard of it an hour ago. But from the guide (this guide) it sounds like there are async I/O.
It also happens that there is a nim port : this one
So I was wondering, does the async magic has something to do with async/await which are keywords not present in the nim port (which is just c2nim). So is it just something that's internal to ZMQ and the API doesn't have to bother about it ?
I thought async/await was a vernacular thing that has to bubble up to the upper most main loop (framework loop) so the API would have to be async-aware.
Is this a complete misconception on my part ?
Native ZeroMQ API supports both blocking and non-blocking I/O-s.
For this purpose, there are flags, where zmq.NOBLOCK could be added, so as to achieve a non-blocking mode of operation.
The respective language-wrapper functionality decides . . .
If I read the nim ZeroMQ-wrapper, that you have mentioned above, it seems to me, that there is a hardcoded blocking version for both send() and recv() function-wrappers.
The wrapper also seems not to support correct wireline message sizing in case a nim-based node of a distributed-system meets another node, which is using ZeroMQ version 2.1.+, which is still interesting and common in heterogeneous distributed-system realms.
ZeroMQ has also a poll() method, equipped with a timeout parameter, so that your multiplexed I/O-operations may yield all wanted ways of how to operate multiple I/O-channels under some soft real-time control constraints.
While the accepted answer was true at the time; async with ZMQ now is built with the wrapper and there are examples provided :
See :
https://github.com/nim-lang/nim-zmq/blob/master/zmq/asynczmq.nim
https://github.com/nim-lang/nim-zmq/blob/master/examples/ex08_async_reqrep.nim
You can also work around the blocking behaviour or ZMQ in order to not block the async-dispatch loop manually with poll / sleepAsync :
let
zmq_timeout = 50
async_loop_time = 450 # spend more time on async stuff than on zmq stuff
var
conn = listen("tcp://127.0.0.1:36000", mode = PAIR=
poller = initZPoll([conn], ZMQ_POLLIN)
if poller.poll(timeout):
if events(poller[0]):
var res = poller[0].receive()
# Do async stuff
else:
waitFor sleepAsync(async_loop_time) # Calling sleepAsync is a trick to make the async dispatch loop progress for a time

SignalR .Net client - how to invoke synchronously and asynchronously

I'm learning SignalR using the .Net client (not javascript), and was hoping for some clarification on how to invoke hub proxy methods in a synchronous or asynchronous manner.
Method with no return value
So far I've been doing something like this:-
myHubProxy.Invoke("DoSomething");
I've found this to be asynchronous, which is fine as it's effectively "fire-and-forget" and doesn't need to wait for a return value. A couple of questions though:-
Are there any implications with wrapping the Invoke in a try..catch block, particularly with it being asynchronous? I might want to know if the call failed.
Are there any scenarios where you would want to call a method that doesn't return a value synchronously? I've seen the .Wait() method mentioned, but I can't think why you would want to do this.
Method with return value
So far I've been using the Result property, e.g.:-
var returnValue = myHubProxy.Invoke<string>("DoSomething").Result;
Console.WriteLine(returnValue);
I'm assuming this works synchronously - after all, it couldn't proceed to the next line until a result had been returned. But how do I invoke such a method asynchronously? Is it possible to specify a callback method, or should I really be using async/await these days (something I confess to still not learning about)?
If you want to write asynchronous code, then you should use async/await. I have an intro on my blog with a number of followup resources at the end.
When you start an asynchronous operation (e.g., Invoke), then you get a task back. The Task type is used for asynchronous operations without a return value, and Task<T> is used for asynchronous operations with a return value. These task types can indicate to your code when the operation completes and whether it completed successfully or with error.
Although you can use Task.Wait and Task<T>.Result, I don't recommend them. For one, they wrap any exceptions in an AggregateException, which make your error handling code more cumbersome. It's far easier to use await, which does not do this wrapping. Similarly, you can register a callback using ContinueWith, but I don't recommend it; you need to understand a lot about task schedulers and whatnot to use it correctly. It's far easier to use await, which does the (most likely) correct thing by default.
The .Result property returns a async Task, so the server requests is still performed async.
There is not reason to hold up a thread for the duration of the call thats why you use async.
If you fire the call on the GUI thread its even more important todo it async because otherwise the GUI will not respond while the call is done
1) Yuo need to use the await keyword if you want try catch blocks to actually catch server faults. Like
try
{
var foo = await proxy.Invoke<string>("Bar");
}
catch (Exception ex)
{
//act on error
}
2) I think you ment to ask if its any reason to call it async? And yes like I said, you do not want to block any threads while the request is being made

Flex - how to abort/stop a RemoteObject method call?

I am using RemoteObjects to call ZendAMF PHP from Flex/Flash Builder 4.6. I want to stop or abort a method call before it sends the request to the server based on an event or similar.
I have a class where I create and store all the RemoteObjects - for example:
activityLogService = new RemoteObject("zend");
activityLogService.endpoint=endpointServer;
activityLogService.addEventListener(FaultEvent.FAULT,faultHandler);
Then later I can simply call this object:
remotingService.activityLogService .getRecords();
I am trying to find a way in my remotingService object to stop the request - and not send anything to the server - for example if some variables are not set properly.
I noticed there is an invoke event:
activityLogService.addEventListener(InvokeEvent.INVOKE,invokeHandler);
However, I can not tell if that's going to stop things at the proper point, or if it's even possible to actually STOP the request - if so, how?
Thanks!
Check out this question
Flex : Is it possible to stop a remote call?
If you're using a RemoteObject you should be able to call
getOperation() method and then cancel() on the corresponding
operation.

AS3 - How to do a synchronous load of an asynchronous call?

I have a function that loads a user object from a web service asynchronously.
I wrap this function call in another function and make it synchronous.
For example:
private function getUser():User{
var newUser:User;
var f:UserFactory = new UserFactory();
f.GetCurrent(function(u:User):void{
newUser = u;
});
return newUser;
}
UserFactory.GetCurrent looks like this:
public function GetCurrent(callback:Function):void{ }
But my understanding is there is no guarantee that when this function gets called, newUser will actually be the new user??
How do you accomplish this type of return function in Flex?
This way madness lies.
Seriously, you're better off not trying to force an asynchronous call into some kind of synchronous architecture. Learn how the event handling system works in your favour and add a handler for the result event. In fact, here's the advice straight from the flexcoders FAQ :
Q: How do I make synchronous data calls?
A: You CANNOT do synchronous calls. You MUST use the result event. No,
you can't use a loop, or setInterval or even callLater. This paradigm is
quite aggravating at first. Take a deep breath, surrender to the
inevitable, resistance is futile.
There is a generic way to handle the asynchronous nature of data service
calls called ACT (Asynchronous Call Token). Search for this in
Developing Flex Apps doc for a full description.
See my answer here:
DDD and Asynchronous Repositories
Flex and Flash Remoting is inherently asynchronous so fighting against that paradigm is going to give you a ton of trouble. Our service delegates return AsyncToken from every method and we've never had a problem with it.
If you want to ensure that the application doesn't render a new view or perform some other logic until the result/fault comes back, you could do the following:
Attach an event listener for a custom event that will invoke your "post result/fault code"
Make the async call
Handle the result/fault
Dispatch the custom event to trigger your listener from #1
Bear in mind this going to lead to a lot of annoying boilterplate code every time you make an async call. I would consider very carefully whether you really need a synchronous execution path.
You can't convert async call into sync one without something like "sleep()" function and as far as I know it is missing in AS3. And yes, it is not guaranteed that newUser would contain user name before return statement.
The AS3 port of the PureMVC framework has mechanisms for implementing synchronous operations in a Model-View-Controller context. It doesn't try to synchronize asynchronous calls, but it lets you add a synchronous application pattern for controlling them.
Here's an example implementation: PureMVC AS3 Sequential Demo.
In this example, five subcommands are run sequentially, together composing a whole command. In your example, you would implement getUser() as a command, which would call commandComplete() in the getURL() (or whatever) callback. This means the next command would be certain that the getUser() operation is finished.

Resources