等待多个异步下载任务 [英] Waiting for multiple asynchronous download tasks
问题描述
我想同时下载一些文件,例如100个文件。所以我决定将我的下载线程添加到一个调度队列,GCD将调整同时运行的线程数。
I want to download some files, for example 100 files, at the same time. So I decided to add my download threads to a dispatch queue, and GCD will adjust how many threads will run at the same time.
这里的问题是:块在 dispatch_async
将立即完成,因为 task
将在另一个线程上运行。因此,如果 urls
的长度为100,它将立即创建100个线程。
The problem here is: the block in dispatch_async
will be completed immediately, because task
will run on another thread. So, if urls
's length is 100, it will create 100 threads immediately.
var queueDownloadTask = dispatch_queue_create("downloadQueue", nil)
for url in urls {
dispatch_async(queueDownloadTask) {
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let fileTransferSession = NSURLSession(configuration: config)
let task = fileTransferSession.downloadTaskWithURL(url, completionHandler: { (responseUrl, response, error) -> Void in
println("completed")
})
task.resume()
}
}
如何在 dispatch_async
中配置块以等待下载任务完成? I不想使用 dispatch_semaphore
,因为它只允许同时运行一个下载任务。
How can I configure the block in dispatch_async
to wait for the download task to complete? I don't want use dispatch_semaphore
, because it only allow run one download task at the same time.
推荐答案
扩展Abhinav'答案,您应该:
To expand on Abhinav's answer, you should:
- 使用
dispatch_group_create()
创建一个组。 - 在开始每个下载任务之前,请先调用
dispatch_group_enter(group)
。 - 致电
dispatch_group_leave(group)
在任务的完成处理程序中。 - 然后调用
dispatch_group_notify(group,queue,^ {... })
将所有任务完成后执行的块排入队列。
- Use
dispatch_group_create()
to create a group. - Call
dispatch_group_enter(group)
before starting each download task. - Call
dispatch_group_leave(group)
inside the task's completion handler. - Then call
dispatch_group_notify(group, queue, ^{ ... })
to enqueue a block that will be executed when all the tasks are completed.
你可以看到这篇文章中的一个例子。
(顺便说一下,连续做100 dispatch_async
的情况并不是真的线程立即。系统仍然保留对用于满足队列的线程数的控制。但是,您的代码不会等待任何任务在返回之前完成,也不会尝试在完成的多个任务之间进行同步。)
(By the way, it's not true that doing 100 dispatch_async
s in a row will create 100 threads immediately. The system still retains control over how many threads to use to satisfy the queue. However, your code does not wait for any of the tasks to complete before it returns, nor does it attempt to synchronize between multiple tasks completing.)
这篇关于等待多个异步下载任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!