 
     private func task(for task: URLSessionTask) -> SessionDataTask? {
 
-        lock.lock()
-        defer { lock.unlock() }
-
         guard let url = task.originalRequest?.url else {
             return nil
         }
+
+        lock.lock()
+        defer { lock.unlock() }
         guard let sessionTask = tasks[url] else {
             return nil
         }

            // No other callbacks waiting, we can clear the task now.
            if !task.containsCallbacks {
                let dataTask = task.task
                self.remove(dataTask, acquireLock: true)
            }
        }
        let token = task.addCallback(callback)

        guard let sessionTask = self.task(for: task) else {
            return
        }
        remove(task)
        sessionTask.onTaskDone.call((result, Array(sessionTask.callbacks)))
    }
}
