Created
February 28, 2022 20:46
-
-
Save christianselig/3596716c876830b2f4683461be15d38a to your computer and use it in GitHub Desktop.
Some questions about async await threading in Swift's new concurrency model.
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
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
❤️
Correction: I tried to prove my claims with some sample code and it turns out
NSURLConnection
does use a separate thread for something. See the screenshot: when I set a breakpoint in one of the delegate calls, there is acom.apple.NSURLConnectionLoader
thread:It's possible this thread does things like setting up the connection, HTTP parsing, etc. This doesn't invalidate everything I said above because it's definitely possible to write asynchronous networking code without any sort of multithreading (e.g. by using the socket APIs directly), but apparently that's not what
NSURLConnection
does. Sorry for leading you on the wrong track.You can also see in the screenshot in the main thread's stack trace that it's using the run loop to invoke the delegate.
__CFRunLoopDoSource
sounds like it's invoking a callback for a run loop source that has new events (the socket).Here's my code (macOS Command Line Project in Xcode):