diff --git a/Foundation/URLSession/URLSessionTask.swift b/Foundation/URLSession/URLSessionTask.swift index 95a24807ad..001bd4ae5a 100644 --- a/Foundation/URLSession/URLSessionTask.swift +++ b/Foundation/URLSession/URLSessionTask.swift @@ -541,24 +541,30 @@ extension _ProtocolClient : URLProtocolClient { session.delegateQueue.addOperation { delegate.urlSession(session, task: task, didCompleteWithError: nil) task.state = .completed - task.workQueue.async { + session.workQueue.async { session.taskRegistry.remove(task) } } case .noDelegate: task.state = .completed - session.taskRegistry.remove(task) + session.workQueue.async { + session.taskRegistry.remove(task) + } case .dataCompletionHandler(let completion): session.delegateQueue.addOperation { completion(`protocol`.properties[URLProtocol._PropertyKey.responseData] as? Data ?? Data(), task.response, nil) task.state = .completed - session.taskRegistry.remove(task) + session.workQueue.async { + session.taskRegistry.remove(task) + } } case .downloadCompletionHandler(let completion): session.delegateQueue.addOperation { completion(`protocol`.properties[URLProtocol._PropertyKey.temporaryFileURL] as? URL, task.response, nil) task.state = .completed - session.taskRegistry.remove(task) + session.workQueue.async { + session.taskRegistry.remove(task) + } } } task._protocol = nil @@ -599,18 +605,20 @@ extension _ProtocolClient : URLProtocolClient { session.delegateQueue.addOperation { delegate.urlSession(session, task: task, didCompleteWithError: error as Error) task.state = .completed - task.workQueue.async { + session.workQueue.async { session.taskRegistry.remove(task) } } case .noDelegate: task.state = .completed - session.taskRegistry.remove(task) + session.workQueue.async { + session.taskRegistry.remove(task) + } case .dataCompletionHandler(let completion): session.delegateQueue.addOperation { completion(nil, nil, error) task.state = .completed - task.workQueue.async { + session.workQueue.async { session.taskRegistry.remove(task) } } @@ -618,7 +626,9 @@ extension _ProtocolClient : URLProtocolClient { session.delegateQueue.addOperation { completion(nil, nil, error) task.state = .completed - session.taskRegistry.remove(task) + session.workQueue.async { + session.taskRegistry.remove(task) + } } } task._protocol = nil