[iOS] GCD And Operation Queue

Dispatch Queues

(1.) 建立一個DispatchQueue

 let queue = DispatchQueue(label: "com.frost.queue")

(2.) Sync

在Sync block完成前, 主執行緒會先暫停

  func syncQueue() {
    let queue = DispatchQueue(label: "com.frost.queue")
    
    queue.sync {
      for i in 0...5 {
        print("\(i)")
      }
    }
    
    for i in 100...105 {
      print("\(i)")
    }
  }
  
  -------------------------------
  Output:
  1
  2
  3
  4
  5
  101
  102
  103
  104
  105
  

(3.) Async

在Sync block執行時, 主執行會繼續執行

 func syncQueue() {
    let queue = DispatchQueue(label: "com.frost.queue")
    
    queue.async {
      for i in 0...5 {
        print("\(i)")
      }
    }
    
    for i in 100...105 {
      print("\(i)")
    }
  }
  
  -------------------------------
  Output:
  1
  2
  101
  102
  3
  4
  103
  104
  5
  105

(3.) Quality Of Service (QoS) 優先級

優先級越高, 越會先被執行.

由高順位至低順位分別為:

  • userInteractive

  • userInitiated

  • default

  • utility

  • background

  • unspecified

ex:

let queue1 = DispatchQueue(label: "com.frost.queue1", qos: DispatchQoS.userInitiated)
let queue2 = DispatchQueue(label: "com.frost.queue2", qos: DispatchQoS.unspecified)

queue1.async {
    for i in 0...5 {
     print("\(i)")
    }
}

queue2.async {
    for i in 100...105 {
     print("\(i)")
    }
}

 -------------------------------
  Output:
  1
  2
  101
  3
  4
  5
  102
  103
  104
  105

(4.) Concurrent Queues

Concurrent Queues會同步執行任務, 不再依序排隊執行

ex: 非Concurrent

let queue = DispatchQueue(label: "com.frost.queue1", qos: .default)

queue.async {
    for i in 0...5 {
     print("\(i)")
    }
}

queue.async {
    for i in 100...105 {
     print("\(i)")
    }
}

 -------------------------------
  Output:
  1
  2
  3
  4
  5
  101
  102
  103
  104
  105

ex: Concurrent

let queue = DispatchQueue(label: "com.frost.queue1", qos: .default, attributes: .concurrent)

queue.async {
    for i in 0...5 {
     print("\(i)")
    }
}

queue.async {
    for i in 100...105 {
     print("\(i)")
    }
}

 -------------------------------
  Output:
  1
  101
  2
  102
  3
  103
  4
  104
  5
  105

延遲執行

// to run something after 0.1 seconds

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    // your code here
}

Main Queues

DispatchQueue.main.async {
        // 更新UI操作
}

Global Queues

DispatchQueue.global().async {

}

Last updated