【发布时间】:2020-03-24 04:20:59
【问题描述】:
如果从同一个线程(线程 1 主线程)调用 uploadFailed(for id: String)、uploadSuccess() 和 updateOnStart(_ id: String),我知道我们不需要同步队列。如果每次上传时从不同的线程调用函数怎么办。我在哪里确保同步?是上传和状态还是只是状态?
enum FlowState {
case started(uploads: [String])
case submitted
case failed
}
class Session {
var state: FlowState
let syncQueue: DispatchQueue = .init(label: "Image Upload Sync Queue",
qos: .userInitiated,
attributes: [],
autoreleaseFrequency: .workItem)
init(state: FlowState) {
self.state = state
}
mutating func updateOnStart(_ id: String) {
guard case .started(var uploads) = state else {
return
}
uploads.append(id)
state = .started(uploads)
}
mutating func uploadFailed(for id: String) {
guard case .started(var uploads) = state else {
return
}
uploads.removeAll { $0 == id }
if uploads.isEmpty {
state = .failed
} else {
state = .started(uploads)
}
}
mutating func uploadSuccess() {
state = .submitted
}
}
我们是否同步uploads 数组操作和如下状态?
syncQueue.sync {
uploads.append(id)
state = .started(uploads)
}
syncQueue.sync {
uploads.removeAll { $0 == id }
if uploads.isEmpty {
state = .failed
} else {
state = .started(uploads)
}
}
或
syncQueue.sync {
state = .started(uploads)
}
syncQueue.sync {
if uploads.isEmpty {
state = .failed
} else {
state = .started(uploads)
}
}
网络调用的完成处理程序可以更新Session 的state 属性。例如,用户选择 10 张图像并上传。完成后,它可能是失败或成功。对于我们上传的每张图片,我们都会缓存资源id,如果上传失败,我们会将其删除。当所有图片上传失败时,我们更新状态.failed。我们只关心上传一张图片。当单张图片上传时,我们将状态更新为.submitted
【问题讨论】:
-
您所说的“是上传和状态还是只是状态?”是什么意思?
-
您能提供您具体用例的背景吗?你想做什么?
-
@JoshWolff 我用更多信息更新了问题
-
“如果每次上传时从不同的线程调用函数怎么办” 也许这似乎是一种肤浅的反应,但我的第一个想法是确保不会发生这种情况是你的工作。 .?
-
回调尚未创建,其他人将处理异步同时上传的上传。这只是一个后备
标签: ios swift synchronized dispatch-queue