Last active
December 23, 2022 05:38
-
-
Save ankittlp/d04b67082c991a684b539cd16cb0d7a2 to your computer and use it in GitHub Desktop.
SomeHeavyOperationTasks
This file contains 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
import Foundation | |
func printWithThreadInfo(tag: String) { | |
print("Thread \(Thread.current) - \(tag) - \(Thread.isMainThread)") | |
} | |
class SomeHeavyOperationTasks { | |
func someHeavySynchronousTask() -> [Int] { | |
var number: [Int] = [] | |
for i in 1...1000 { | |
number.append(i) | |
} | |
printWithThreadInfo(tag: "someHeavySynchronousTask") | |
return number | |
} | |
func someHeavyAsynchronousCallBackTask(_ completionHandler: ([Int]) -> Void) { | |
printWithThreadInfo(tag: "someHeavyAsynchronousCallBackTask - Start") | |
DispatchQueue.global(qos: .userInitiated).async { | |
printWithThreadInfo(tag: "someHeavyAsynchronousCallBackTask - inside DispatchQueue.global") | |
var number: [Int] = [] | |
for i in 1...1000 { | |
number.append(i) | |
} | |
} | |
printWithThreadInfo(tag: "someHeavyAsynchronousCallBackTask - after DispatchQueue.global") | |
} | |
// 1 Defined a heavy task asynchronous function with `async` | |
func someHeavyAsynchronousConcurrencyTask(start:Int, end: Int) async -> [Int] { | |
printWithThreadInfo(tag: "someHeavyAsynchronousConcurrencyTask - Start from \(start)") | |
// 2 create a task to start the heavy operation. Using await here creats a suspension point where the control of thread is passed back to OS to perform some other important task. While our function is waiting for Task to get complete. | |
let number = await Task { () -> [Int] in | |
printWithThreadInfo(tag: "someHeavyAsynchronousConcurrencyTask - inside Task start from \(start)") | |
var number: [Int] = [] | |
for i in start...end { | |
number.append(i) | |
} | |
printWithThreadInfo(tag: "someHeavyAsynchronousConcurrencyTask - inside Task before return - \(start)") | |
return number | |
}.value | |
// 3 Once Task is complete, suspension is revoked and it is to notice that OS may resume on any other arbitary thread not just the thread which starts the task. | |
printWithThreadInfo(tag: "someHeavyAsynchronousConcurrencyTask - after await \(start)") | |
return number | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment