How to create dispatch queue in Swift 3

2018-12-31 18:06发布

问题:

In Swift 2, I was able to create queue with the following code:

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

But this doesn\'t compile in Swift 3.

What is the preferred way to write this in Swift 3?

回答1:

Creating a concurrent queue

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

}  

Create a serial queue

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

}

Get main queue asynchronously

DispatchQueue.main.async {

}

Get main queue synchronously

DispatchQueue.main.sync {

}

To get one of the background thread

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

}

Xcode 8.2 beta 2:

To get one of the background thread

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

}

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

If you want to learn about using these queues .See this answer



回答2:

Compiles under Swift 3. This example contains most of the syntax that we need.

QoS - new quality of service syntax

weak self - to disrupt retain cycles

if self is not available, do nothing

async global background queue - for network query

async main queue - for touching the UI.

Of course, you need to add some error checking to this...

DispatchQueue.global(qos: .background).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:

Compiled in 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()
            }

        }
    }

}


回答4:

I did this and this is especially important if you want to refresh your UI to show new data without user noticing like in UITableView or UIPickerView.

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


回答5:

Since the OP question has already been answered above I just want to add some speed considerations:

It makes a lot of difference what priority class you assign to your async function in DispatchQueue.global.

I don\'t recommend running tasks with the .background thread priority especially on the iPhone X where the task seems to be allocated on the low power cores.

Here is some real data from a computationally intensive function that reads from an XML file (with buffering) and performs data interpolation:

Device name / .background / .utility / .default / .userInitiated / .userInteractive

  1. iPhone X: 18.7s / 6.3s / 1.8s / 1.8s / 1.8s
  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

Note that the data set is not the same for all devices. It\'s the biggest on the iPhone X and the smallest on the iPhone 5s.



回答6:

   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

I re-worked your code in Xcode 8, Swift 3 and the changes are marked in contrast to your Swift 2 version.



回答7:

 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
}

//use Operation Queue if you need to populate the objects(labels, imageview, textview) on your viewcontroller



回答8:

Swift 3

you want call some closure in swift code then you want to change in storyboard ya any type off change belong to view your application will crash

but you want to use dispatch method your application will not crash

async method

DispatchQueue.main.async 
{
 //Write code here                                   

}

sync method

DispatchQueue.main.sync 
{
     //Write code here                                  

}


回答9:

DispatchQueue.main.async(execute: {

// write code

})

Serial Queue :

let serial = DispatchQueue(label: \"Queuename\")

serial.sync { 

 //Code Here

}

Concurrent queue :

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

concurrent.sync {

 //Code Here
}


回答10:

For Swift 3

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


回答11:

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

 // your code

 }


回答12:

it is now simply:

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

the default is serial, to get concurrent, you use the optional attributes argument .concurrent



回答13:

You can create dispatch queue using this code in 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*/
}


回答14:

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