开发者

How can I sequence asynchronous background tasks with GCD?

I am using GCD on iOS to perform a a time-consuming task on a background thread. The API has a start method that takes two blocks as arguments, both called on the main queue. The first is called when the task starts and the second when the task finishes. This all works.

I actually need to do several of these time-consuming tasks. The API lets me start them all at the same time and then wait for each to finish and update the UI via the blocks. They run concurrently.

However what I actually I want to do is to sequence the time-consuming tasks (still starting each using the API described) so that I can start them all at the same time, have the first one run and give me its call-backs, then have the second one run and give me its call-backs, etc. until all are done.

What is the best way to achieve this with GCD and blocks?

If the tasks were synchronous, I'd just have a loop that ran each in turn, and run all of that asynchronously. But I have call-backs, so that will not work. I'd prefer not to have to chain them, since the object that makes all of this happen could disappear once it has s开发者_StackOverflow社区tarted the sequence of events.


You can create your own serial queue that will execute in FIFO order with dispatch_queue_create. You DO NOT need to specify that it is a serial queue. It will act this way by default.

Sample queue creation:

dispatch_queue_t my_q = dispatch_queue_create("Serial",NULL);

You own this queue, so failing to release it (with dispatch_release) will leak it.

More info is in Apple's docs here.


Is there a particular reason you have to use GCD? Sounds like NSOperationQueue with concurrency of 1 is exactly what you want.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜