In this article, we will learn how to limit the number of ongoing network requests using a DispatchSemaphore
.
在本文中,我们将学习如何使用DispatchSemaphore
限制正在进行的网络请求的数量。
Limiting resource-heavy operations allows us to manage thread resources more efficiently. For example, when you have a task to simultaneously fetch ten high-quality images, it is useful to allow the execution of only one or two image loading operations at a time.
限制资源密集型操作可以使我们更有效地管理线程资源。 例如,当您有一个任务要同时获取十个高质量图像时,一次仅执行一个或两个图像加载操作非常有用。
In short, this is what you will master in this tutorial:
简而言之,这是您将在本教程中掌握的内容:
Executing tasks on a background
DispatchQueue
.在后台
DispatchQueue
上执行任务。Leveraging a
DispatchSemaphore
and setting the max number of concurrent operations.利用
DispatchSemaphore
并设置最大并发操作数。Understanding the difference between using
sync
andasync
executions.了解使用
sync
执行和async
执行之间的区别。
开始吧 (Let’s Start)
First, let’s create a URL
, a background DispatchQueue
, and a DispatchSemaphore
with a value of 2:
首先,我们创建一个URL
,一个背景DispatchQueue
和一个DispatchSemaphore
,其值为2:
import UIKit
let url = URL(string: "https://source.unsplash.com/random/5120x1000")!
let queue = DispatchQueue.global(qos: .background)
let semaphore = DispatchSemaphore(value: 2)
The value
parameter of the semaphore indicates the maximum number of concurrent operations allowed. In other words, we will allow only two images to be fetched at the same time.
信号量的value<