为什么使用Swift DispatchGroup将CPU加载到1000%?

问题描述

我有一些代码可以异步调用外部库以从图像文件中读取EXIF关键字:

  func readKeywords()
  {
    keywordsForSelectedItems.removeAll()
    
    let group: dispatchGroup = .init()
    
    let queue: dispatchQueue = .init(label: "com.keywords")
    
    collectionView.selectionIndexPaths.forEach
    {
      indexPath in
      
      let item = self.collectionView.item(at: indexPath) as! CollectionViewItem
      
      let url = item.url!
      
      group.enter()
      
      queue.async(group: group)
      {
        do
        {
          try ExifReader.keywords(for: url)
          {
            keywords in
            
            if let keywords = keywords,keywords.count > 0
            {
              self.keywordsForSelectedItems.append(keywords)
            }
            
            group.leave()
          }
        }
        catch
        {
          print(error.localizedDescription)
        }
      }
    }

    group.notify(queue: queue)
    {
      let firstValue: [String]? = self.keywordsForSelectedItems.first
      {
        keywords in
        
        keywords.count > 0
      }
        
      if firstValue != nil
      {
        let keywords = self.keywordsForSelectedItems.reduce(Set(firstValue!))
        {
          result,item in
          
          result.union(item)
        }
        
        dispatchQueue.main.async
        {
          self.tokenView.objectValue = [String](keywords).sorted()
        }
      }
    }
  }

添加代码之前,一切正常,并且图像在CollectionView中完美显示

但是,自从添加代码以来,一旦调用代码cpu风扇便会开始运行,有时甚至高达1000%,并且它可以阻止通常在后台加载图像的其他异步进程。

有人有什么主意吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)