Swift:在后台同步执行代码; queue.sync无法正常工作 [英] Swift: synchronously perform code in background; queue.sync does not work as I would expect

查看:165
本文介绍了Swift:在后台同步执行代码; queue.sync无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在后台同步执行一些代码,我真的认为这是可行的方法:

I would like to perform some code synchronously in the background, I really thought this is the way to go:

let queue = DispatchQueue.global(qos: .default)
queue.async {
    print("\(Thread.isMainThread)")
}

,但这会打印true,除非我使用queue.async. async是不可能的,因为这样代码将并行执行.如何实现在后台同步运行多个块?

but this prints true unless I use queue.async. async isn't possible as then the code will be executed in parallel. How can I achieve running multiple blocks synchronously in the background?

我想要实现的目标:将我的应用程序中的事件与设备日历同步,这发生在后台.可以从不同的地方多次调用执行此操作的方法,因此我想保持此操作有序并在后台进行.

What I would like to achieve: synchronize events in my app with the devices calendar, which happens in the background. The method which does this can be called from different places multiple times so I would like to keep this in order and in the background.

推荐答案

异步执行不是您的问题,因为您只关心代码块相对于彼此(而不是相对于主线程)的执行顺序.您不应该阻塞主线程,实际上是DispatchQueue.main而不是DispatchQueue.global.

Async execution isn't your problem, since you only care about the order of execution of your code blocks relative to each other but not relative to the main thread. You shouldn't block the main thread, which is in fact DispatchQueue.main and not DispatchQueue.global.

您应该做的是在串行队列上异步执行代码,这样就不会阻塞主线程,但仍要确保代码块按顺序执行.

What you should do is execute your code on a serial queue asynchronously, so you don't block the main thread, but you still ensure that your code blocks execute sequentially.

您可以使用以下代码来实现:

You can achieve this using the following piece of code:

let serialQueue = DispatchQueue(label: "serialQueue")
serialQueue.async{  //call this whenever you need to add a new work item to your queue
    //call function here
}

这篇关于Swift:在后台同步执行代码; queue.sync无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆