Does I/O operation (e.g. a network request) block main thread if a concurrent chunk of code performing the I/O dispatched on main thread?
Depends on how the I/O is implemented. URLSession
implements its own threading outside the Swift concurrency thread pool, so it never blocks. If there are other async
I/O APIs, they may or may not implement their own threading, so without knowing the implementation details it's impossible to know whether they'll block. I/O like the various disk reading Data
APIs will block, as they're synchronous.
If you have more questions there are quite a few WWDC videos and quite a lot of written documentation that explains how things work.
As a general rule, when calling some framework API, if it offers an async
method that you await
, it will not block. It’s the whole point of providing interfaces that support async
-await
.
Specifically, URLSession
does not block.
You only need to be careful with what you do with the results. If parsing a huge file, processing an image, etc., then you might want to follow the Swift concurrency contract to never impede forward progress and move that slow and synchronous work off the main actor. But URLSession
will not block the current actor.
It depends.
URLSession based API's don't block the current thread while socket's recv
or old Foundation API's like NSData.dataWithContentsOfURL
or its Swift counterpart - do.
File IO tends to be more blocking than network IO.