 
     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
         }

        return DownloadTask(sessionTask: task, cancelToken: token)
    }

    private func remove(_ task: URLSessionTask, acquireLock: Bool) {
        guard let url = task.originalRequest?.url else {
            return
        }

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