Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell what queue a completionHandler executes on?

Looking at the documentation for URLSession.dataTask it's clear this function is called asynchronously but there's no mention of whether the completionHandler returns to the main thread, the thread which called it or remains on the thread the dataTaskOperation was performed on.

Is there a general convention to expect here?

  let task = URLSession.shared().dataTask(with: request) {
        //What Thread are we on here?
    }
like image 782
Declan McKenna Avatar asked Feb 23 '18 16:02

Declan McKenna


2 Answers

From the documentation of the completionHandler parameter of URLSession dataTask:

This handler is executed on the delegate queue.

So the next question is, what is the delegate queue? That all depends on how the URLSession was setup. You are using the shared session which sets a nil delegate queue. The documentation for the queue parameter of the init method states:

If nil, the session creates a serial operation queue for performing all delegate method calls and completion handler calls.

So the code you posted results in the completion handler being called on a background serial queue.

like image 180
rmaddy Avatar answered Nov 09 '22 20:11

rmaddy


URLSession

In the documentation it says...

This handler is executed on the delegate queue.

And looking at the delegate queue...

All delegate method calls and completion handlers related to the session are performed on this queue. The session object keeps a strong reference to this queue until your app exits or the session object is deallocated. If you do not invalidate the session, your app leaks memory until it exits.

Note

This queue must be set at object creation time and may not be changed.

And looking at the init method...

It doesn't actually say anything about what type of queue is used...

Hmm...

As pointed out by @rmaddy a serial queue is created by the session so that would run on a background thread.

Conventions

As for conventions... there isn't really one.

If you write your own there are things to consider... is the completion likely going to update the UI? Will the completion do lots of data processing etc... and you can decide from there.

like image 1
Fogmeister Avatar answered Nov 09 '22 19:11

Fogmeister