我可以取消 JSONEncoder Swift 吗?

Can I cancel a JSONEncoder Swift?

我有一个 JSONEncoder 编码一个 20mb 的文件,这需要很长时间才能处理。如果它正在处理的数据发生变化,我想取消编码,然后重新启动编码过程,但我想不出办法来做到这一点。有任何想法吗? 我可以再次调用 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)
            }
        }
    }

您可以使用 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

什么是操作队列:

An operation queue invokes its queued Operation objects based on their priority and readiness. After you add an operation to a queue, it remains in the queue until the operation finishes its task. You can’t directly remove an operation from a queue after you add it.

参考链接: