简体   繁体   English

如何使用GCD排序异步后台任务?

[英]How can I sequence asynchronous background tasks with GCD?

I am using GCD on iOS to perform aa time-consuming task on a background thread. 我在iOS上使用GCD在后台线程上执行一项耗时的任务。 The API has a start method that takes two blocks as arguments, both called on the main queue. 该API有一个start方法,该方法采用两个块作为参数,均在主队列上调用。 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. API使我可以同时启动它们,然后等待它们完成并通过块更新UI。 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. 但是,我实际上想要做的是对耗时的任务进行排序(仍然使用所描述的API来启动每个任务),以便我可以同时启动所有任务,运行第一个并给我回叫,然后进行第二次操作,并给我回电,等等,直到完成所有操作。

What is the best way to achieve this with GCD and blocks? 用GCD和块实现此目标的最佳方法是什么?

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 started the sequence of events. 我不希望将它们链接起来,因为一旦开始事件序列,使所有这些事情发生的对象可能会消失。

You can create your own serial queue that will execute in FIFO order with dispatch_queue_create . 您可以创建自己的串行队列,并使用dispatch_queue_create以FIFO顺序执行。 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. 您拥有此队列,因此未能释放它(使用dispatch_release )将泄漏它。

More info is in Apple's docs here . 更多信息在此处的Apple文档中

Is there a particular reason you have to use GCD? 您有使用GCD的特殊原因吗? Sounds like NSOperationQueue with concurrency of 1 is exactly what you want. 听起来像NSOperationQueue并发为1正是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM