GCD (Grand Central Dispatch):- GCD is used in iOS to introduce concurrency and parallelism in iOS Applications so that multiple heavy tasks do in the background, in result smooth user experience in Apps, the main thread is unaffected by heavy background tasks.
GCD introduce in iOS 4 for avoiding the serial execution of threads.
GCD maintains the queue of tasks to operate them. Once the task inserted in queues it starts its execution. it is up to us whether we execute tasks execute as synchronously or asynchronously.
Create the Dispatch Queue-
let dispatchQueue = DispatchQueue(lable: "dispatchQueueName")
Once DispatchQueue created we can start executing tasks synchronously or asynchronously (as per our need).
Types of DispatchQueue:- DispatchQueue are three types are given below
1- Main Queue
2- Global Queue
3- Custom Queue
1- Main Queue:- When the system launched the iOS application then it creates a serial queue and that queue binds the application's main thread. We use this queue used to mostly perform UI related updates in the application.
How we use the Main Queue? -
DispatchQueue.main.async {
// code to be executed
}
2- Global Queue:- There are four global concurrent queues which are provided and shared by the system.
Quality of service attributes indicates the priority of the task in the queue.
a) User-Interactive
b) User-Initiate
c) Utility
d) Background
a) User-Interactive- In this queue mostly used to perform UI updations. As per the apples guidline UI updation must not done in background thread so this queue has hight priority with relatively small size.
How we use -
DispatchQueue.global(qos: .userInteractive).sync {
// code to be executed
}
b) User-Initiate- The tasks in this queue must execute immediately as they react user interaction events link reacting to a specific button click.These task also a high priority taks.
How we use -
DispatchQueue.global(qos: .userInitiate).sync {
// code to be executed
}
c) Utility- We use this queue for long running opreations in the background. The tasks in this queue is low priority tasks like downloading files in the background.
How we use -
DispatchQueue.global(qos: .utility).sync {
// code to be executed
}
c) Background- Those task that takes mintues to hours to complete the tasks comes under this queue. These taks are heavy operations that performs in the background without affecting applications performance like backup, indexing comes under this queue. These tasks are low priority.
How we use -
DispatchQueue.global(qos: .background).sync {
// code to be executed
}

Comments
Post a Comment