问题描述
我有一些需要下载的照片,但是下载功能一次只能下载一张照片。我希望在下载其他照片之前确保下载功能已完成。我创建.initialyInactive DispatchQueue,并在下载功能的完成块中激活了队列。这很不错,照片已下载,但是我的问题是如何取消下载过程?我可以以某种方式删除未激活的队列吗?
我的代码逻辑如下所示。
I have array of photos that needs to be downloaded, but download function can download only one photo at a time. I neeed to make sure that download function is completed before I call it for other photo. I create .initialyInactive DispatchQueue and queue is activated in completion block of download function. This is woking, and photos are downloaded, but my question is how to cancel download process? Can I somehow to remove not activated queues?
My code logic looks something like this..
func downloadPhoto(photo: Photo, completion: (_ success: Bool) -> Void) {
... completion(true) ..
}
for photo in photos {
let queue = DispatchQueue(label: "Download queue\(counter)", qos: .userInitiated, attributes: .initiallyInactive)
self.inactiveQueues[counter] = queue
queue.async {
self.downloadPhoto(photo: photo) { (success) in
nextQueue?.activate()
if success {
...
} else {
...
}
}
}
解决我的问题的其他方法也很棒。谢谢。
Ant other solution to my problem is great too. Thanks.
推荐答案
有几种选择:
-
从历史上看,我们将使用自定义的异步
Operation
子类。请参见(或请参见(用于替代AsynchronousOperation
的实现)。这使我们可以取消操作,并且我们可以轻松地控制并发程度。
Historically we’d use a custom, asynchronous,
Operation
subclass. See https://stackoverflow.com/a/38469350/1271826 (or see https://stackoverflow.com/a/48104095/1271826 for alternateAsynchronousOperation
implementation). That gives us a cancelable operation and we can easily control the degree of concurrency.
如果要一次下载一个,可以设置队列的 maxConcurrentOperationCount
到1。然后,您可以将下载操作添加到单个 OperationQueue
中,如果要取消下载操作,请致电。
If you want to download them one at a time, you could set the queue’s maxConcurrentOperationCount
to 1. Then you can just add your download operations to a single OperationQueue
, and if you want to cancel them, you’d call queue.cancelAllOperations()
.
如果您的目标是iOS 13及更高版本,请使此操作更加容易。请参阅,以了解如何使用Combine下载一系列图像的示例(两者
If you are targeting iOS 13 and later, Combine makes this even easier. See https://stackoverflow.com/a/61195234/1271826 for example of downloading a series of images using Combine (both sequentially as well as with a controlled degree of concurrency).
我已经说了所有这些,我鼓励您需要重新考虑顺序下载图像的选择。在我的中,将允许的最大并发率提高到6,导致下载速度总体上是串行下载速度的两倍行为。
All of this having been said, I’d encourage you to reconsider the choice to download the images sequentially. In my random test, increasing the max allowed concurrency to 6 resulted in downloads that were, overall, twice as fast as the serial behavior.
这篇关于最初删除非活动队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!