Multi threading? Concurrency? Asynchronous task? GCD (Grand Central Dispatch) ? in Swift Programming
Introduction of Grand Central Dispatch
Grand central dispatch is the powerful api for multitasking with sync and async programming in iOS.
The DispatchQueue API like a company 🏢..Who having staff units like junior level and senior level workers 👷🏼. So now the company can take both heavy and light work with
there team.
// Perform your async code here
}
Concurrenct- It’s starting multiple tasks at the same time but not guarantee for the finish at same time. Its can finish any order.
Sync vs Async
Sync - When a work item is executed synchronously with the sync method, the program waits until execution finishes before the method call returns.
Code Example Sync
func syncWork(){
let northZone = DispatchQueue(label: "perform_task_with_team_north")
let southZone = DispatchQueue(label: "perform_task_with_team_south")
northZone.sync {
for numer in 1...3{ print("North \(numer)")}
}
southZone.sync {
for numer in 1...3{ print("South \(numer)") }
}
}
//Call Func here
syncWork()
//Output
// North 1
// North 2
// North 3
// South 1
// South 2
// South 3
Async - execute asynchronously with the async method, the method call returns immediately.
Code Example Async
func asyncWork(){
let northZone = DispatchQueue(label: "perform_task_with_team_north")
let southZone = DispatchQueue(label: "perform_task_with_team_south")
northZone.async {
for numer in 1...3{ print("North \(numer)") }
}
southZone.async {
for numer in 1...3{ print("South \(numer)") }
}
}
//Call Async Task
asyncWork()
//OutPut
// North 1
// South 1
// North 2
// South 2
// North 3
// South 3
Perform network task with UI updates -
Global Queue -Using to perform non-UI work in the background.
Main Queue -Using to update the UI after completing work in a task on a concurrent queue.
List of DispatchQueue Priority -
.userInitiated
.default
.utility
.background
.unspecified
Perform background Quality of Service (QOS) task -
// Call your background task
DispatchQueue.main.async {
// UI Updates here for task complete.
}
}
DispatchQueue with delay ⏳
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
//Perform code here
}
Dispatch Groups 👨👨👦👦
dispatchGroup.enter()
loadUseractivities { dispatchGroup.leave() }
dispatchGroup.enter()
loaduserComments { dispatchGroup.leave() }
dispatchGroup.notify(queue: .main) {
print("all activities complete ")
}
Comments
Post a Comment