Created
October 18, 2023 03:03
-
-
Save Myrrel/4b56df64632c4b441ed5ce9d672675cf to your computer and use it in GitHub Desktop.
Grand Central Dispatch examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // # Serial queue | |
| // Creating a custom serial queue with a specific label | |
| let customQueue = DispatchQueue(label: "com.example.myqueue") | |
| // Adding a task to the custom queue | |
| customQueue.sync { | |
| // Perform some work here | |
| } | |
| // # Concurrent queue | |
| // Creating a custom concurrent queue with a specific label | |
| let customConcurrentQueue = DispatchQueue(label: "com.example.myconcurrentqueue", attributes: .concurrent) | |
| // Adding tasks to the custom concurrent queue | |
| customConcurrentQueue.async { | |
| // Task 1: Perform some work here | |
| } | |
| customConcurrentQueue.async { | |
| // Task 2: Perform some work here | |
| } | |
| customConcurrentQueue.async { | |
| // Task 3: Perform some work here | |
| } | |
| // # Perform background tasks and also update UI. | |
| DispatchQueue.global(qos: .background).async { | |
| // Call your background task | |
| DispatchQueue.main.async { | |
| // UI Updates here for task complete. | |
| } | |
| } | |
| // # DispatchQueue with delay | |
| let deadlineTime = DispatchTime.now() + .seconds(1) | |
| DispatchQueue.main.asyncAfter(deadline: deadlineTime) { | |
| //Perform code here | |
| } | |
| // # Sync and Async | |
| func syncExamples() { | |
| let people = DispatchQueue(label: "syncExamples.queue.people") | |
| let age = DispatchQueue(label: "syncExamples.queue.age") | |
| people.sync { | |
| for name in ["Jack", "John", "Macheal"] { | |
| print(name) | |
| } | |
| } | |
| age.sync { | |
| for age in [29, 34, 73] { | |
| print(age) | |
| } | |
| } | |
| } | |
| syncExamples() | |
| func asyncExamples() { | |
| let people = DispatchQueue(label: "syncExamples.queue.people") | |
| let age = DispatchQueue(label: "syncExamples.queue.age") | |
| people.async { | |
| for name in ["Jack", "John", "Macheal"] { | |
| print(name) | |
| } | |
| } | |
| age.async { | |
| for age in [29, 34, 73] { | |
| print(age) | |
| } | |
| } | |
| } | |
| asyncExamples() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment