如何在Swift 3中创建调度队列

在Swift 2中,我能够使用以下代码创建队列:

let concurrentQueue = dispatch_queue_create("com.swift3.imageQueue", DISPATCH_QUEUE_CONCURRENT)

但这在Swift 3中无法编译。

在Swift 3中编写此代码的首选方式是什么?


#1楼

创建并发队列

let concurrentQueue = DispatchQueue(label: "queuename", attributes: .concurrent)
concurrentQueue.sync {

}  

创建一个串行队列

let serialQueue = DispatchQueue(label: "queuename")
serialQueue.sync { 

}

异步获取主队列

DispatchQueue.main.async {

}

同步获取主队列

DispatchQueue.main.sync {

}

获取后台线程之一

DispatchQueue.global(qos: .background).async {

}

Xcode 8.2 beta 2:

获取后台线程之一

DispatchQueue.global(qos: .default).async {

}

DispatchQueue.global().async {
    // qos' default value is ´DispatchQoS.QoSClass.default`
}

如果您想了解有关使用这些队列的信息,请参见此答案。


#2楼

Swift 3下编译。 此示例包含我们需要的大多数语法。

QoS-新的服务质量语法

weak self -破坏保留周期

如果没有自我,什么也不做

async global background queue -用于网络查询

async main queue -用于触摸UI。

当然,您需要为此添加一些错误检查...

DispatchQueue.global(qos: .utility).async { [weak self] () -> Void in

    guard let strongSelf = self else { return }

    strongSelf.flickrPhoto.loadLargeImage { loadedFlickrPhoto, error in

        if error != nil {
            print("error:\(error)")
        } else {
            DispatchQueue.main.async { () -> Void in
                activityIndicator.removeFromSuperview()
                strongSelf.imageView.image = strongSelf.flickrPhoto.largeImage
            }
        }
    }
}

#3楼

现在很简单:

let serialQueue = DispatchQueue(label: "my serial queue")

默认为串行,要并发,请使用可选属性参数.concurrent


#4楼

在XCode 8,Swift 3中编译https://github.com/rpthomas/Jedisware

 @IBAction func tap(_ sender: AnyObject) {

    let thisEmail = "emailaddress.com"
    let thisPassword = "myPassword" 

    DispatchQueue.global(qos: .background).async {

        // Validate user input

        let result = self.validate(thisEmail, password: thisPassword)

        // Go back to the main thread to update the UI
        DispatchQueue.main.async {
            if !result
            {
                self.displayFailureAlert()
            }

        }
    }

}

#5楼

您可以在swift 3.0中使用此代码创建调度队列

DispatchQueue.main.async
 {
   /*Write your code here*/
 }

   /* or */

let delayTime = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)                   
DispatchQueue.main.asyncAfter(deadline: delayTime)
{
  /*Write your code here*/
}

#6楼

我做到了这一点,如果您想刷新UI来显示新数据而无需用户注意,例如UITableView或UIPickerView,这尤其重要。

    DispatchQueue.main.async
 {
   /*Write your thread code here*/
 }

#7楼

   let concurrentQueue = dispatch_queue_create("com.swift3.imageQueue", DISPATCH_QUEUE_CONCURRENT) //Swift 2 version

   let concurrentQueue = DispatchQueue(label:"com.swift3.imageQueue", attributes: .concurrent) //Swift 3 version

我在Xcode 8,Swift 3中重新编写了您的代码,并且所做的更改与您的Swift 2版本形成了鲜明的对比。


#8楼

DispatchQueue.main.async(execute: {

// write code

})

串行队列:

let serial = DispatchQueue(label: "Queuename")

serial.sync { 

 //Code Here

}

并发队列:

 let concurrent = DispatchQueue(label: "Queuename", attributes: .concurrent)

concurrent.sync {

 //Code Here
}

#9楼

 DispatchQueue.main.async {
          self.collectionView?.reloadData() // Depends if you were populating a collection view or table view
    }


OperationQueue.main.addOperation {
    self.lblGenre.text = self.movGenre
}

//如果您需要在viewcontroller上填充对象(标签,imageview,textview),请使用Operation Queue


#10楼

DispatchQueue.main.async(execute: {
   // code
})

#11楼

迅捷3

您想在快速代码中调用一些闭包,然后您要在情节提要中进行更改,即任何类型的更改都属于您的应用程序将崩溃的原因

但是您想使用调度方法,您的应用程序将不会崩溃

异步方法

DispatchQueue.main.async 
{
 //Write code here                                   

}

同步方式

DispatchQueue.main.sync 
{
     //Write code here                                  

}

#12楼

对于Swift 3

   DispatchQueue.main.async {
        // Write your code here
    }

#13楼

 let newQueue = DispatchQueue(label: "newname")
 newQueue.sync { 

 // your code

 }

#14楼

由于上面已经回答了OP问题,所以我只想补充一些速度方面的注意事项:

DispatchQueue.global中分配给异步函数的优先级类别有很多不同。

我不建议以.background线程优先级运行任务,尤其是在iPhone X上,该任务似乎分配在低功耗内核上。

这是来自计算密集型函数的一些实际数据,该函数从XML文件读取(带有缓冲)并执行数据插值:

设备名称/ 装置技术领域 / .utility / .DEFAULT / .userInitiated / .userInteractive

  1. iPhone X:18.7秒/6.3秒/1.8秒/1.8秒/1.8秒
  2. iPhone 7:4.6s / 3.1s / 3.0s / 2.8s / 2.6s
  3. iPhone 5s:7.3s / 6.1s / 4.0s / 4.0s / 3.8s

请注意,所有设备的数据集都不相同。 它在iPhone X上最大,在iPhone 5s上最小。


#15楼

迅速更新5

串行队列

let serialQueue = DispatchQueue.init(label: "serialQueue")
serialQueue.async {
    // code to execute
}

并发队列

let concurrentQueue = DispatchQueue.init(label: "concurrentQueue", qos: .background, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil)

concurrentQueue.async {
// code to execute
}

Apple文档

参量

标签

附加到队列的字符串标签,以便在调试工具(如仪器,样本,堆栈快照和崩溃报告)中唯一地标识它。 由于应用程序,库和框架都可以创建自己的调度队列,因此建议使用反向DNS命名方式(com.example.myqueue)。 此参数是可选的,可以为NULL。

服务质量

与队列关联的服务质量级别。 此值确定系统安排任务执行的优先级。 有关可能值的列表,请参见DispatchQoS.QoSClass。

属性

与队列关联的属性。 包括并发属性以创建可以同时执行任务的调度队列。 如果省略该属性,则分派队列将顺序执行任务。

自动释放频率

自动释放队列调度的块创建的对象的频率。 有关可能的值的列表,请参见DispatchQueue.AutoreleaseFrequency

目标

要在其上执行块的目标队列。 如果希望系统提供适合当前对象的队列,请指定DISPATCH_TARGET_QUEUE_DEFAULT。

发布了0 篇原创文章 · 获赞 2 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/104246596