Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add lock to fix thread racing #1089

Merged
merged 1 commit into from
Jan 12, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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