GCD:如何从串行队列中删除等待任务? [英] GCD: How to remove waiting tasks from serial queue?

查看:364
本文介绍了GCD:如何从串行队列中删除等待任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先我创建一个这样的串行队列

First I create a serial queue like this

static dispatch_queue_t queue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL);

然后,在某个未知的时间点,任务会像这样添加到队列中

then, at some unknown point in time a task gets added to the queue like this

dispatch_async(queue, ^{
    // do something, which takes some time
});

如果第一项任务尚未完成,新任务将等到第一项任务完成(即当然是串口队列的用途。)

If the first task hasn't finished yet, the new task will wait until the first completes (that's of course what a serial queue is for).

但是如果我在队列中添加5个新任务,而原来的第一个任务仍在运行,我不想要执行新的任务1号,然后是2号,然后是3号,依此类推,但想要完成任务1到4,并在原始第一个任务完成后直接开始执行5号任务。

But if I add 5 new tasks to the queue, while the original first one is still running, I don't want to execute new task no.1, then no.2, then no.3 and so on, but want to get rid of tasks 1 to 4 and directly start executing task no.5 after the original first task has finished.

换句话说,我想在队列中弹出任何等待任务(不是当前正在运行的任务),如果我添加一个新任务。

In other words, I want to pop any waiting task (not the one that is currently running) off the queue, if I add a new one.

是否有内置机制或我是否必须自己实现?对于后者,我如何识别队列中的单个任务并将其删除?

Is there a build in mechanism for this or do I have to implement this myself? And for the latter, how would I identify single tasks inside a queue and remove them?

推荐答案

一旦提交了一个块一个GCD调度队列,它将运行。没有办法取消它。如你所知,你可以实现自己的机制来提前中止块执行。

Once a block has been submitted to a GCD dispatch queue, it will run. There is no way to cancel it. You can, as you know, implement your own mechanism to "abort" the block execution early.

更简单的方法是使用 NSOperationQueue ,因为它已经提供了取消挂起操作(即那些尚未运行的操作)的实现,并且您可以使用new-ish addOperationWithBlock轻松地将块排入队列方法。

An easier way to do this would be to use NSOperationQueue, as it already provides an implementation for canceling pending operations (i.e., those not yet running), and you can easily enqueue a block with the new-ish addOperationWithBlock method.

虽然 NSOperationQueue 是使用GCD实现的,但我发现GCD更容易使用在大多数情况下。但是,在这种情况下,我会认真考虑使用 NSOperationQueue ,因为它已经处理了取消挂起操作。

Though NSOperationQueue is implemented using GCD, I find GCD much easier to use in most cases. However, in this case, I would seriously consider using NSOperationQueue because it already handles canceling pending operations.

这篇关于GCD:如何从串行队列中删除等待任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆