How does URLSessionTask run

Viewed 2703

Say I have created an instance of URLSessionTask:

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in 
   print (\(Thread.current))
}
// I start the task by
task.resume()

I want to understand whether the URLSessionTask instance is running on main thread by default or in background thread. So, I print the Thread.current .

When I run my code, it print out:

<NSThread: 0x170273980>{number = 4, name = (null)}

My questions are:

  1. which thread the URLSessionTask is running by default? Main thread or background thread?

  2. Why current thread shows null in thread name? Does it mean it is running in background thread by default? (I see name="main" for print on main thread)

  3. In general, is it necessary to run URLSessionTask with GCD in order to force it run in background thread or not? I am asking this because I saw some tutorials doesn't use GCD to run URLSessionTask, they only use GCD to run completion handler in main thread.

1 Answers
Related