Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

arnieterm

macrumors regular
Original poster
Aug 28, 2008
201
0
How to make an asynchronous call embedded within a synchronous method so that the method can wait for a response in asynchronous call and proceed only when it receives a response. I am looking for an alternate to avoid using while loops.
As the asynchronous request/response are scheduled through run loops so how can we solve this problem?
Thanks
Arnieterm
 
Split the sync method into two and have the async callback that tells you it's complete call the second part of the method?

If that doesn't work you'll have to be a lot more specific about the calls you are making (post code)
 
If you can't break the portions of your app which depend on this call into asynchronous state-driven blocks (because your porting legacy code, etc.), another option is to do the async call sequences in a run loop in another thread, then have the existing synchronous thread block on a semaphore until the async call thread has reached some end state.
 
The asynchronous portion is related to NSStream
Code:
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode{

The problem is that a method say "GetData" [Being a synchronous] with return type NSArray* initiates streaming procces with below given code

Code:
isStreamErrorEncountered = NO;	
	[NSStream getStreamsToHostNamed: hostName port: hostPort inputStream: &iStream outputStream:&oStream];
	[iStream retain];
	[oStream retain];
	[iStream setDelegate: self];
	[oStream setDelegate: self];
	[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode: NSDefaultRunLoopMode];
	[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode: NSDefaultRunLoopMode];
	[oStream open];
	[iStream open];

Here "iStream", "oStream" are static NSInputStream and NSOutputStream variables.
When I get the response via the event handler [or time out whichever earlier] only then I need to return NSArray from the synchronous method.
Can you explain your suggestion using a simple example

Thanks
Arnieterm
 
I would suggest reworking your execution logic so that GetData does not require the return of the NSArray but instead some other method is responsible for the NSArray's population. Then you can probably use one of the delegate methods of an async operation to trigger what is done once the NSArray is populated. Take a close look at the SeismicXML sample app which uses this approach quite nicely.
 
Thanks for your reply. I will try to redesign my logic. So far I am stick to this situation as I have to make changes in an existing application that is making synchronous web service calls. Now that code has to include this async stuff too. Can you tell what can be the maximum size of input/output buffer though I am using 1024 at present.

Thanks
Arnieterm
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.