Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save codeactual/a3b70167480079da2bb9eb9f4c5a728d to your computer and use it in GitHub Desktop.

Select an option

Save codeactual/a3b70167480079da2bb9eb9f4c5a728d to your computer and use it in GitHub Desktop.
Some questions about async await threading in Swift's new concurrency model.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Task {
// 1️⃣❓ UIViewController is in a MainActor context, so this Task
// will inherit that, so the following pretend expensive call will
// be on the main thread and likely block?
ExpensiveOperationPerformer.doExpensiveLoopAndPrint()
}
Task.detached {
// 2️⃣❓ Is this guaranteed to be off the main thread, so perhaps a
// better way to do a one-off, expensive operation? If it's not
// guaranteed, how would I ensure that? Wrap it in an actor
// instead of a class? What if it's not my class/I can't
// change the code?
ExpensiveOperationPerformer.doExpensiveLoopAndPrint()
}
Task {
ExpensiveOperationPerformer.printSomeNetworkData()
}
}
}
class ExpensiveOperationPerformer {
@MainActor
static func printSomeNetworkData() async throws {
let url = URL(string: "https://example.com/example.json")!
// 3️⃣❓ Will this time consuming network call be guaranteed to NOT
// execute on main, despite the MainActor context? Or will it block?
let (data, response) = try await URLSession.data(for: url)
print(data)
}
static func doExpensiveLoopAndPrint() async {
let upperEnd = 9_999_999_999
var sum = 0
for i in 0 ..< upperEnd {
sum += 1
}
print(sum)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment