ソースを参照

Use the same queue for all prefetchers

onevcat 7 年 前
コミット
50991bb612

+ 5 - 8
Sources/Networking/ImagePrefetcher.swift

@@ -31,6 +31,10 @@ import AppKit
 import UIKit
 #endif
 
+// The dispatch queue to use for handling resource process, so downloading does not occur on the main thread
+// This prevents stuttering when preloading images in a collection view or table view.
+private let prefetchQueue = DispatchQueue(label: "com.onevcat.Kingfisher.PrefetchQueue")
+
 /// Progress update block of prefetcher. 
 ///
 /// - `skippedResources`: An array of resources that are already cached before the prefetching starting.
@@ -57,10 +61,7 @@ public class ImagePrefetcher {
     
     /// The maximum concurrent downloads to use when prefetching images. Default is 5.
     public var maxConcurrentDownloads = 5
-    
-    // The dispatch queue to use for handling resource process, so downloading does not occur on the main thread
-    // This prevents stuttering when preloading images in a collection view or table view.
-    private var prefetchQueue: DispatchQueue
+
     
     private let prefetchResources: [Resource]
     private let optionsInfo: KingfisherParsedOptionsInfo
@@ -138,10 +139,6 @@ public class ImagePrefetcher {
         prefetchResources = resources
         pendingResources = ArraySlice(resources)
         
-        // Set up the dispatch queue that all our work should occur on.
-        let prefetchQueueName = "com.onevcat.Kingfisher.PrefetchQueue"
-        prefetchQueue = DispatchQueue(label: prefetchQueueName)
-        
         // We want all callbacks from our prefetch queue, so we should ignore the callback queue in options.
         // Add our own callback dispatch queue to make sure all internal callbacks are
         // coming back in our expected queue.

+ 16 - 0
Tests/KingfisherTests/ImagePrefetcherTests.swift

@@ -298,4 +298,20 @@ class ImagePrefetcherTests: XCTestCase {
         
         waitForExpectations(timeout: 3, handler: nil)
     }
+
+    func testPrefetchMultiTimes() {
+        let exp = expectation(description: #function)
+        let group = DispatchGroup()
+
+        testURLs.forEach { stub($0, data: testImageData) }
+        for _ in 0..<10000 {
+            group.enter()
+            let prefetcher = ImagePrefetcher(resources: testURLs) { _, _, _ in
+                group.leave()
+            }
+            prefetcher.start()
+        }
+        group.notify(queue: .main) { exp.fulfill() }
+        waitForExpectations(timeout: 3, handler: nil)
+    }
 }