开发者

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:

  1. Some thread calls [Foo poll].
  2. The poll method starts a couple of HTTP requests which runs in the background. In this case ASIHTTPRequest.
  3. The requests eventually calls [Foo onRequestComplete] which parses the response. On error [Foo onRequestError] is called. This is a second return path.
  4. Then more calls are done to the server, with callbacks and more return paths.
  5. Eventually saving some stuff to disk.
  6. 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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜