Skip to content

Commit

Permalink
Merge pull request onevcat#1089 from onevcat/fix/racing
Browse files Browse the repository at this point in the history
Add lock to fix thread racing
  • Loading branch information
onevcat authored Jan 12, 2019
2 parents dc40ce5 + 8e67cae commit 7b71070
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions Sources/Networking/SessionDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ class SessionDelegate: NSObject {
return DownloadTask(sessionTask: task, cancelToken: token)
}

func remove(_ task: URLSessionTask, acquireLock: Bool) {
private func remove(_ task: URLSessionTask, acquireLock: Bool) {
guard let url = task.originalRequest?.url else {
return
}
Expand All @@ -98,7 +98,7 @@ class SessionDelegate: NSObject {
if acquireLock { lock.unlock() }
}

func task(for task: URLSessionTask) -> SessionDataTask? {
private func task(for task: URLSessionTask) -> SessionDataTask? {
guard let url = task.originalRequest?.url else {
return nil
}
Expand All @@ -112,6 +112,8 @@ class SessionDelegate: NSObject {
}

func task(for url: URL) -> SessionDataTask? {
lock.lock()
defer { lock.unlock() }
return tasks[url]
}

Expand Down Expand Up @@ -165,9 +167,10 @@ extension SessionDelegate: URLSessionDataDelegate {
task.didReceiveData(data)

if let expectedContentLength = dataTask.response?.expectedContentLength, expectedContentLength != -1 {
let dataLength = Int64(task.mutableData.count)
DispatchQueue.main.async {
task.callbacks.forEach { callback in
callback.onProgress?.call((Int64(task.mutableData.count), expectedContentLength))
callback.onProgress?.call((dataLength, expectedContentLength))
}
}
}
Expand Down

0 comments on commit 7b71070

Please sign in to comment.