swift3多线程学习笔记

当通过url来给UIImageView设置图片的时候需要下载图片,如果在主线程中执行下载图片并设置图片会导致在下载图片的时候界面卡死。通过多线程可以解决下载任务导致界面卡死的问题。

1、创建并使用额外的Serie Queue

letseriesQueue =DispatchQueue(label:"textGCD")

seriesQueue.async{

  letimage =DownloadManager.download(url:self.imageUrls[0])

  DispatchQueue.main.sync{

    self.image.image= image

    self.image.clipsToBounds=true

  }
}

2、使用Concurrent queue并行处理

let curQueue = DispatchQueue.global()
curQueue.async {
    let image = DownloadManager.download(url: self.imageUrls[0])
    DispatchQueue.main.sync {
        self.image1.image = image
        self.image1.clipsToBounds = true
    }
}

3、使用Operation Queue进行多任务处理

let operationQueue = OperationQueue()
operationQueue.addOperation {
    let image = DownloadManager.download(url: self.imageUrls[0])
    OperationQueue.main.addOperation({
        self.image1.image = image
        self.image1.clipsToBounds = true
        
    })
}

let operation2 = BlockOperation.init {
    let image = DownloadManager.download(url: self.imageUrls[1])
    OperationQueue.main.addOperation({
        self.image2.image = image
        self.image2.clipsToBounds = true
    })
}

let operation3 = BlockOperation.init {
    let image = DownloadManager.download(url: self.imageUrls[2])
    OperationQueue.main.addOperation({
        self.image3.image = image
        self.image3.clipsToBounds = true
    })
}

let operation4 = BlockOperation.init {
    let image = DownloadManager.download(url: self.imageUrls[3])
    OperationQueue.main.addOperation({
        self.image4.image = image
        self.image4.clipsToBounds = true
    })
}

operation2.addDependency(operation3)
operation3.addDependency(operation4)

operation2.completionBlock = { print("task completion")}
operationQueue.addOperation(operation2)
operationQueue.addOperation(operation3)
operationQueue.addOperation(operation4)

你可能感兴趣的:(swift3多线程学习笔记)