使用 Swift 的新 async/await 功能,我想模拟串行队列的调度行为(类似于过去使用 aDispatchQueue或 的方式)。OperationQueue
稍微简化一下我的用例,我有一系列异步任务,我想从调用站点触发并在完成时获得回调,但根据设计,我想一次只执行一个任务(每个任务取决于之前的任务完成)。
如今,这是通过将Operations放置到OperationQueue带有 a的 上maxConcurrentOperationCount = 1,以及Operation在适当的时候使用 的依赖功能来实现的。我已经使用现有的基于闭包的入口点构建了一个异步/等待包装器,await withCheckedContinuation但我正在尝试找出如何将整个方法迁移到新系统。
那可能吗?它是否有意义,或者我从根本上违背了新的异步/等待并发系统的意图?
我已经深入研究了 using Actors 但据我所知,没有办法用这种方法真正强制/期望串行执行。
--
更多上下文 - 这包含在一个网络库中,其中今天的每个操作都是针对一个新请求。该操作会执行一些请求预处理(如果适用,请考虑身份验证/令牌刷新),然后触发请求并继续执行下一个操作,从而避免在不需要时重复进行身份验证预处理。从技术上讲,每个操作并不知道它依赖于先前的操作,但操作队列的调度强制串行执行。
添加下面的示例代码:
// Old entry point
func execute(request: CustomRequestType, completion: ((Result<CustomResponseType, Error>) -> Void)? = nil) {
let operation = BlockOperation() {
// do preprocessing and ultimately generate a URLRequest
// We have a URLSession instance reference in this context called session
let …Run Code Online (Sandbox Code Playgroud) 我点击了 10 次 Web 服务 url 并得到响应。我正在使用Alamofire和SwiftyJSON。这是我的控制器代码
class ViewController: UIViewController {
let dispatchGroup = DispatchGroup()
var weatherServiceURL = "http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22"
override func viewDidLoad() {
super.viewDidLoad()
start()
}
func start() {
weatherService()
dispatchGroup.notify(queue: .main) {
print("All services complete")
}
}
func weatherService() {
for i in 1...10 {
dispatchGroup.enter()
APIManager.apiGet(serviceName: self.weatherServiceURL, parameters: ["counter":i]) { (response:JSON?, error:NSError?, count:Int) in
if let error = error {
print(error.localizedDescription)
return
}
guard let response = response else { return }
print("\n\(response) \n\(count) …Run Code Online (Sandbox Code Playgroud) grand-central-dispatch ios dispatch-async swift dispatchworkitem