【问题标题】:Image loading/caching off the main thread图像加载/缓存主线程
【发布时间】:2021-03-18 04:02:29
【问题描述】:

我正在编写一个自定义图像获取器来获取我的收藏视图所需的图像。下面是我的图像获取器逻辑

class ImageFetcher {

    /// Thread safe cache that stores `UIImage`s against corresponding URL's
    private var cache = Synchronised([URL: UIImage]())

    /// Inflight Requests holder which we can use to cancel the requests if needed
    /// Thread safe
    private var inFlightRequests = Synchronised([UUID: URLSessionDataTask]())
    
    
    func fetchImage(using url: URL, completion: @escaping (Result<UIImage, Error>) -> Void) -> UUID? {
        /// If the image is present in cache return it
        if let image = cache.value[url] {
            completion(.success(image))
        }
        
        let uuid = UUID()
        
        let dataTask = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
            guard let self = self else { return }
            defer {
                self.inFlightRequests.value.removeValue(forKey:uuid )
            }
            
            if let data = data, let image = UIImage(data: data) {
                self.cache.value[url] = image
                
                DispatchQueue.main.async {
                    completion(.success(image))
                }
                return
            }
            
            guard let error = error else {
                // no error , no data
                // trigger some special error
                return
            }
            
            
            // Task cancelled do not send error code
            guard (error as NSError).code == NSURLErrorCancelled else {
                completion(.failure(error))
                return
            }
        }
        
        dataTask.resume()
        
        self.inFlightRequests.value[uuid] = dataTask
        
        return uuid
    }
    
    func cancelLoad(_ uuid: UUID) {
        self.inFlightRequests.value[uuid]?.cancel()
        self.inFlightRequests.value.removeValue(forKey: uuid)
    }
}

这是一个提供访问缓存所需的线程安全性的代码块

/// Use to make a struct thread safe
public class Synchronised<T> {
    private var _value: T
    
    private let queue = DispatchQueue(label: "com.sync", qos: .userInitiated, attributes: .concurrent)
    
    public init(_ value: T) {
        _value = value
    }
    
    public var value: T {
        get {
            return queue.sync { _value }
        }
        set { queue.async(flags: .barrier) { self._value = newValue }}
    }
}

我没有看到所需的滚动性能,我预计这是因为当我尝试访问缓存时我的主线程被阻塞 (queue.sync { _value })。我正在从 collectionView 的 cellForRowAt 方法调用 fetchImage 方法,但我似乎找不到将其从主线程分派出去的方法,因为我需要请求的 UUID,因此我可以取消请求如果需要的话。关于如何将其从主线程中移除的任何建议,或者是否有任何建议以更好的方式构建它?

【问题讨论】:

    标签: ios multithreading grand-central-dispatch data-synchronization barrier


    【解决方案1】:

    我不认为您的滚动性能与fetchImage 有关。虽然Synchronized 中存在适度的性能问题,但可能不足以解释您的问题。话虽如此,这里有几个问题,但阻塞主队列似乎不是其中之一。

    更可能的罪魁祸首可能是检索大于图像视图的资产(例如,小图像视图中的大资产需要调整大小,这可能会阻塞主线程)或获取逻辑中的一些错误。当您说“没有看到所需的滚动性能”时,它是卡顿还是缓慢? “滚动性能”问题的性质将决定解决方案。


    一些不相关的观察:

    1. Synchronised,与字典一起使用,不是线程安全的。是的,value 的 getter 和 setter 是同步的,但不是该字典的后续操作。它也非常低效(虽然,解释您遇到的问题的效率可能不够低)。

      我建议不要同步整个字典的检索和设置,而是做一个同步的字典类型:

      public class SynchronisedDictionary<Key: Hashable, Value> {
          private var _value: [Key: Value]
      
          private let queue = DispatchQueue(label: "com.sync", qos: .userInitiated, attributes: .concurrent)
      
          public init(_ value: [Key: Value] = [:]) {
              _value = value
          }
      
          // you don't need/want this
          //
          // public var value: [Key: Value] {
          //     get { queue.sync { _value } }
          //     set { queue.async(flags: .barrier) { self._value = newValue } }
          // }
      
          subscript(key: Key) -> Value? {
              get { queue.sync { _value[key] } }
              set { queue.async(flags: .barrier) { self._value[key] = newValue } }
          }
      
          var count: Int { queue.sync { _value.count } }
      }
      

      在我的测试中,在发布版本中,这大约快了 20 倍。而且它是线程安全的。

      但是,我们的想法是您不应该公开底层字典,而只是公开同步类型管理字典所需的任何接口。您可能希望在上面添加其他方法(例如removeAll 或其他),但上面的内容应该足以满足您的直接目的。您应该能够执行以下操作:

      var dictionary = SynchronizedDictionary<String, UIImage>()
      
      dictionary["foo"] = image
      imageView.image = dictionary["foo"]
      print(dictionary.count)
      

      或者,您可以将字典的所有更新分派到主队列(请参阅下面的第 4 点),那么您根本不需要这种同步的字典类型。

    2. 您可以考虑使用NSCache,而不是您自己的字典来保存图像。您希望确保响应内存压力(清空缓存)或某个固定的总成本限制。另外,NSCache 已经是线程安全的。

    3. fetchImage 中,您有多个不调用完成处理程序的执行路径。按照惯例,您需要确保始终调用完成处理程序。例如。如果调用者在获取图像之前启动了一个微调器,并在完成处理程序中停止它怎么办?如果您可能不调用完成处理程序,那么微调器也可能永远不会停止。

    4. 同样,在调用完成处理程序的地方,并不总是将其分派回主队列。我要么总是分派回主队列(使调用者不必这样做),要么只是从当前队列中调用完成处理程序,但只将其中一些分派到主队列会引起混淆。


    FWIW,您可以创建单元测试目标并通过使用concurrentPerform 测试字典的大规模并发修改来演示原始SynchronisedSynchronisedDictionary 之间的区别:

    // this is not thread-safe if T is mutable
    
    public class Synchronised<T> {
        private var _value: T
    
        private let queue = DispatchQueue(label: "com.sync", qos: .userInitiated, attributes: .concurrent)
    
        public init(_ value: T) {
            _value = value
        }
    
        public var value: T {
            get { queue.sync { _value } }
            set { queue.async(flags: .barrier) { self._value = newValue }}
        }
    }
    
    // this is thread-safe dictionary ... assuming `Value` is not mutable reference type
    
    public class SynchronisedDictionary<Key: Hashable, Value> {
        private var _value: [Key: Value]
    
        private let queue = DispatchQueue(label: "com.sync", qos: .userInitiated, attributes: .concurrent)
    
        public init(_ value: [Key: Value] = [:]) {
            _value = value
        }
    
        subscript(key: Key) -> Value? {
            get { queue.sync { _value[key] } }
            set { queue.async(flags: .barrier) { self._value[key] = newValue } }
        }
    
        var count: Int { queue.sync { _value.count } }
    }
    
    class SynchronisedTests: XCTestCase {
        let iterations = 10_000
    
        func testSynchronised() throws {
            let dictionary = Synchronised([String: Int]())
    
            DispatchQueue.concurrentPerform(iterations: iterations) { i in
                let key = "\(i)"
                dictionary.value[key] = i
            }
    
            XCTAssertEqual(iterations, dictionary.value.count)  //  XCTAssertEqual failed: ("10000") is not equal to ("834")
        }
    
        func testSynchronisedDictionary() throws {
            let dictionary = SynchronisedDictionary<String, Int>()
    
            DispatchQueue.concurrentPerform(iterations: iterations) { i in
                let key = "\(i)"
                dictionary[key] = i
            }
    
            XCTAssertEqual(iterations, dictionary.count)        // success
        }
    }
    

    【讨论】:

    • 感谢您的回答。我看到的问题是口吃,正如您所怀疑的,问题确实是获取大于图像视图大小的资产。获取正确的资产大小解决了这个问题。是的,我也在考虑使用 NSCache 进行缓存。但是,我不明白Synchronised 与字典配对时如何不是线程安全的。
    • Yes, the getter and setter for value is synchronized, but not the subsequent manipulation of that dictionary.“字典的后续操作”是什么意思,`SynchronisedDictionary`是如何解决问题的?
    • 在原始版本中,您正在同步 value getter 和 setter,但您在同步机制之外操作字典(带有下标)。 SynchronisationDictionary 解决了这个问题,它从不暴露底层的 Swift Dictionary,而是提供了自己的同步下标运算符。它也更有效,因为Dictionary 值类型不会被传递和复制。简而言之,当尝试同步可变类型时,永远不要暴露底层对象,而是提供你自己的方法/操作符来执行突变。
    • 感谢@Rob 的解释。你是最棒的!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 2019-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多