在后台线程上的NSBlockOperation之后立即在主线程上运行一个块

Jon*_* H. 2 macos cocoa multithreading grand-central-dispatch swift

在我的项目中,我使用后台线程运行一个操作NSBlockOperation:

var operationQueue = NSOperationQueue()
var iop = NSBlockOperation(block: { self.reloadSize() /*calculation...*/ })
operationQueue.addOperation(iop)
Run Code Online (Sandbox Code Playgroud)

在后台线程中的计算完成后,我需要立即调用:table.reloadData()在NSTableView上.我会在同一个线程中执行此操作,但是,由于自动布局问题,必须在主线程上重新加载表.如何跨两个线程完成这种异步关系?

Rob*_*Rob 6

两种可能的方法:

  1. 从块内部调度表的重新加载:

    let operationQueue = NSOperationQueue()
    let operation = NSBlockOperation() {
        self.reloadSize()
        ...
        dispatch_async(dispatch_get_main_queue()) { // or you can use NSOperationQueue.mainQueue().addOperationWithBlock()
            self.table.reloadData()
        }
    }
    operationQueue.addOperation(operation)
    
    Run Code Online (Sandbox Code Playgroud)

    或者只是使用addOperationWithBlock:

    let operationQueue = NSOperationQueue()
    operationQueue.addOperationWithBlock() {
        self.reloadSize()
        ...
        dispatch_async(dispatch_get_main_queue()) { // or you can use NSOperationQueue.mainQueue().addOperationWithBlock()
            self.table.reloadData()
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 根据这个创建一个新的操作:

    let operationQueue = NSOperationQueue()
    
    let operation = NSBlockOperation() {
        self.reloadSize()
        ...
    }
    
    let completionOperation = NSBlockOperation() {
        self.table.reloadData()
    }
    
    completionOperation.addDependency(operation)
    
    operationQueue.addOperation(operation)
    NSOperationQueue.mainQueue().addOperation(completionOperation)
    
    Run Code Online (Sandbox Code Playgroud)

就个人而言,我通常倾向于第一种方法,尽管后一种方法在更复杂的情况下可能是有用的(例如,完成操作取决于许多其他操作).