Does NSURLConnection block the main thread?

2020-01-31 07:50发布

问题:

I'm using NSURLConnection in an iPhone application and the interface seems to slow down after sending initWithRequest: to my NSURLConnection instance. I'm not sure if this is occurring because my processing code is taking a long time to handle the response, or if it's because NSURLConnection is blocking the main thread.

Can anyone confirm that NSURLConnection will create the connection and wait for data on a separate thread, and then call its delegate methods on the main thread?

Thanks!

回答1:

NSURLConnection supports two modes of operation: asynchronous and synchronous. Neither uses separate threads at all. They both use just one thread, that being whatever thread you run them in.

In synchronous mode, NSURLConnection will block whatever thread you run it in. Asynchronous mode uses the run loop to behave (from the developer's perspective) similarly to a background thread but with lower overhead and without any thread-safety issues. If using asynchronous mode, you want to run it in the main thread. It won't block anything.

If your interface is slowing down, that is not consistent with using NSURLConnection synchronously, which would instead cause your interface to stop completely until the request is complete.



回答2:

If you follow apples example on NSURLConnection the call will be handled in a different thread than the main thread.