swift - 通用大中央调度

标签 swift asynchronous swift3 grand-central-dispatch completionhandler

我的代码设置如下。据我了解,队列 1 应该完成所有操作,然后移至队列 2。但是,一旦我的异步操作开始,queue2 就会开始。这违背了 GCD 的目的……我做错了什么?这输出:

完成了吗
队列 2
然后一段时间后,打印图像下载成功

..我想说清楚,如果我在 queue1 中放入其他代码,例如 print("test") 或循环 0..10 打印 i,所有这些操作将在移动到 queue2 之前完成。似乎异步下载搞砸了,我该如何解决这个问题?任何地方都没有文档,我使用了来自 AppCoda 的非常有用的指南 http://www.appcoda.com/grand-central-dispatch/

    let queue1 = DispatchQueue(label: "com.matt.myqueue1")
    let queue2 = DispatchQueue(label: "com.matt.myqueue2")
    let group1 = DispatchGroup()
    let group2 = DispatchGroup()

    let item = DispatchWorkItem{
        // async stuff happening like downloading an image  
        // print success if image downloads       
    }

    queue1.sync(execute: item)

    item.notify(queue1, execute: {
        print("did this finish?")
    })


    queue2.sync {
        print("queue2")
    }

最佳答案

let item = DispatchWorkItem{
    // async stuff happening like downloading an image  
    // print success if image downloads       
}

好的,定义它,但还没有运行。

queue1.sync(execute: item)

执行 item开始它的异步事件。之后立即返回。这里没有说“等待那些不相关的异步事件完成”。系统甚至没有办法知道您调用的函数内部还有其他异步调用。它如何知道 object.doit() 是否包含异步调用(以及这些调用是否是您打算等待的异步调用)?它只知道 item 何时返回,继续。

这就是 group1 的用途(您似乎没有将它用于任何用途)。在这些“异步发生的事情”中的某个地方,你应该通过离开组来告诉系统它已完成。 (我不知道 group2 是做什么用的。它也从未被使用过。)

item.notify(queue1, execute: {
    print("did this finish?")
})

item 已经完成。我们知道它必须已经完成,因为它是使用sync 运行的,并且直到它的项目完成才会返回。所以这个 block 将立即安排在 queue1 上。

queue2.sync {
    print("queue2")
}

完全不相关并且可以在“完成此操作”代码之前或之后运行,我们在 queue2 上安排了一个 block 。

你的意思可能是:

let queue1 = DispatchQueue(label: "com.matt.myqueue1")
let group1 = DispatchGroup()

group1.enter()

// Kick off async stuff.
// These usually return quickly, so there's no need for your own queue.
// At some point, when you want to say this is "done", often in some 
// completion handler, you call group1.leave(), for example:
       ... completionHandler: { group1.leave() }

// When all that finishes, print
group.notify(queue: queue1) { print("did this finish?") }

关于swift - 通用大中央调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41494904/

相关文章:

ios - 为什么一个 View Controller 创建了两次?

c# - 使用(而非滥用)ContinueWith

c# - 如果我在未定义为任务的 IQueryable 上使用 await + ToListAsync() 是否正确

swift - Apple Mach-O 链接器错误(静态,不是 ld)

xcode - NSImages 到 PDF 并在 Swift 中合并它们

ios - tableView(_ tableView : UITableView, didSelectRowAt indexPath: IndexPath) 当我将 UITapGestureRecognizer 添加到自定义 UITableViewCell 时不起作用

ios - 如何使用 Swift 在 iOS 中以编程方式打开显示和亮度中的 NightShift

json - 无法从符合 Equatable 的对象向下转换为 AnyObject

ios - 快速从 TableViewCell 获取 TableView 部分标题

python - 尝试实现扭曲延迟列表时的奇怪行为