How to manage background requests reliably?
I need to asynchronously run a query against a http server and handle the response. The query is really a pretty large chain of method calls with callbacks. This adds complexity because there are a lot of return开发者_运维知识库 paths during the chain of calls.
It should not be possible to start a new request until the current one is completely completed.
Here is the general outline:
- Some thread calls
[Foo poll]. - The
pollmethod starts a couple of HTTP requests which runs in the background. In this case ASIHTTPRequest. - The requests eventually calls
[Foo onRequestComplete]which parses the response. On error[Foo onRequestError] is called. This is a second return path. - Then more calls are done to the server, with callbacks and more return paths.
- Eventually saving some stuff to disk.
- The poll is complete
Here is the catch: During these steps, calls to poll should be ignored (returned) or blocked until the poll is complete.
How can you make sure the poll function blocks or no-ops while another poll is running?
Simply use NSLock.
In [Foo poll]:
if ([lock tryLock]) {
// Do your stuff
}
In [Foo onRequestComplete]:
[lock unlock];
加载中,请稍侯......
精彩评论