首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我可以取消JSONEncoder Swift吗?

我可以取消JSONEncoder Swift吗?
EN

Stack Overflow用户
提问于 2021-06-23 10:32:25
回答 1查看 111关注 0票数 0

我有一个编码20 to文件的JSONEncoder,它需要很长时间才能处理。如果它正在处理的数据发生了变化,我想取消编码,重新启动编码过程,但是我想不出有什么方法可以做到这一点。有什么想法吗?我可以再次调用JSONEncoder.encode,但现在我将有两个30秒的进程运行,内存和处理器开销将增加一倍。很高兴能取消上一次。

编辑:你们中的一些人要求看我的编码器。我认为这是造成最大瓶颈的原因.

代码语言:javascript
复制
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)
            }
        }
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-23 10:48:12

您可以使用OperationQueue并将长时间运行的任务添加到操作队列中。

代码语言:javascript
复制
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()
}

您还可以随时使用以下代码取消该任务:

代码语言:javascript
复制
//Whenever you want to cancel the task, you can do it like this
queue?.cancelAllOperations()
queue = nil

什么是操作队列:

操作队列根据其优先级和准备状态调用其排队操作对象。将操作添加到队列后,该操作将一直保留在队列中,直到操作完成其任务为止。添加后不能直接从队列中移除操作。

参考链接:

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68098098

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档