我有一个编码20 to文件的JSONEncoder,它需要很长时间才能处理。如果它正在处理的数据发生了变化,我想取消编码,重新启动编码过程,但是我想不出有什么方法可以做到这一点。有什么想法吗?我可以再次调用JSONEncoder.encode,但现在我将有两个30秒的进程运行,内存和处理器开销将增加一倍。很高兴能取消上一次。
编辑:你们中的一些人要求看我的编码器。我认为这是造成最大瓶颈的原因.
func encode(to encoder: Encoder) throws {
try autoreleasepool {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(brush, forKey: .brush)
if encoder.coderType == CoderType.export {
let bezierPath = try NSKeyedUnarchiver.unarchivedObject(ofClass: UIBezierPath.self, from: beziersData)
let jsonData = try UIBezierPathSerialization.data(with: bezierPath, options: UIBezierPathWritingOptions.ignoreDrawingProperties)
let bezier = try? JSONDecoder().decode(DBBezier.self, from: jsonData)
try container.encodeIfPresent(bezier, forKey: .beziersData)
} else {
try container.encodeIfPresent(beziersData, forKey: .beziersData)
}
}
}发布于 2021-06-23 10:48:12
您可以使用OperationQueue并将长时间运行的任务添加到操作队列中。
var queue: OperationQueue?
//Initialisation
if queue == nil {
queue = OperationQueue()
queue?.maxConcurrentOperationCount = 1
}
queue?.addOperation {
//Need to check the isCanceled property of the operation for stopping the ongoing execution in any case.
self.encodeHugeJSON()
}您还可以随时使用以下代码取消该任务:
//Whenever you want to cancel the task, you can do it like this
queue?.cancelAllOperations()
queue = nil什么是操作队列:
操作队列根据其优先级和准备状态调用其排队操作对象。将操作添加到队列后,该操作将一直保留在队列中,直到操作完成其任务为止。添加后不能直接从队列中移除操作。
参考链接:
https://stackoverflow.com/questions/68098098
复制相似问题