IOS DispatchWorkItem

Definition:

The work you want to perform, encapsulated in a way that lets you attach a completion handle or execution dependencies.
A DispatchWorkItem encapsulates work to be performed on a dispatch queue or within a dispatch group. You can also use a work item as a DispatchSource event, registration, or cancellation handler.

Note:

WorkItem的功能就是把一項可能重複執行的task封裝起來,且能在multithread上執行(p.s. 透過DispatchQueue or DispatchGroup)並具備同步、取消的功能。

WorkItem的操作都只針對單一task,如果同時要管理多個task,則還是要使用DispatchGroup or DispatchSemaphore來管理。

Function:

  • Creating a Work Item
  • Executing the Work Item
  • Adding a Completion Handler
  • Waiting for the Completion of a Work Item
  • Canceling a Work Item

Sample code:

// Creating a Work Item
let workItem = DispatchWorkItem {
    print("This is my task")
}

// Executing the Work Item
workItem.perform()
DispatchQueue.global().async(execute: workItem)

// Waiting for the Completion of a Work Item
workItem.wait()

// Canceling a Work Item
workItem.cancel()

// Adding a Completion Handler
workItem.notify(queue: DispatchQueue.main) {
    print("Finish executing work item")
}

Ref: https://developer.apple.com/documentation/dispatch/dispatchworkitem