Skip to content

Instantly share code, notes, and snippets.

@christianselig
Created February 28, 2022 20:46
Show Gist options
  • Save christianselig/3596716c876830b2f4683461be15d38a to your computer and use it in GitHub Desktop.
Save christianselig/3596716c876830b2f4683461be15d38a 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)
}
}
@ole
Copy link

ole commented Mar 8, 2022

❤️

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 a com.apple.NSURLConnectionLoader thread:

Screen Shot 2022-03-08 at 16 43 27

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):

import Foundation

final class Loader: NSObject, NSURLConnectionDataDelegate {
  var connection: NSURLConnection? = nil

  func start() {
    let url = URL(string: "https://google.com")!
    connection = NSURLConnection(request: URLRequest(url: url), delegate: self)
  }

  func connection(_ connection: NSURLConnection, didReceive data: Data) {
    print(#function, data)
  }

  func connection(_ connection: NSURLConnection, didFailWithError error: Error) {
    print(#function, error)
  }
}

let loader = Loader()
loader.start()

RunLoop.current.run()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment