Note: If you are a beginner and you find it difficult to understand things written in this article. Feel free to ask questions in the Comment section.
To Read, How to use GCD (Grand Central Dispatch) in Swift? - Synchronous & Asynchronous Programming Tutorial. Click Here.
To Read, Difference between Concurrent Queue and Serial Queue. Click Here.
To Read, How to group dispatch queues in Swift? Click Here.
To Read, What is QoS (Quality of Service) in GCD? Click Here.
Remember, you can do it. 😉
What is DispatchWorkItem?
DispatchWorkItem is used to store a task on a dispatch queue for later use, and you can perform operations several operations on it, you can even cancel the task if it is not required later in the code.
Let me give you an example.
let queue = DispatchQueue(label: "com.swiftpal.dispatch.workItem")
// Create a work item
let workItem = DispatchWorkItem() {
print("Stored Task")
}
// Task 1
queue.async(execute: workItem)
// Task 2
queue.asyncAfter(deadline: DispatchTime.now() + 1, execute: workItem)
// Work Item Cancel
workItem.cancel()
// Task 3
queue.async(execute: workItem)
if item.isCancelled {
print("Task was cancelled")
}
/* Output:
Stored Task
Task was cancelled
*/
You may find this a little confusing, so please read the next upcoming lines carefully.
As usual, we started with creating a queue, and then we created our DispatchWorkItem object with a single line of code waiting to be executed.
Next, we created two tasks before cancelling the work item and then we created another task after cancelling the work item.
But, if you see the output, only one task is executed, the rest of them were cancelled as Task 2 was supposed to execute after a second, and Task 3 was initialized after cancelling the work item.
I hope I was able to explain to you guys the use of DispatchWorkItem. If you liked reading my article, Subscribe.
If you have any suggestions or questions, Feel free to connect me on Twitter. 😉
To Read, How to avoid Thread Explosion and Deadlock with GCD in Swift? Click Here.