How to create dispatch queue in Swift 3

前端 未结 15 1882
余生分开走
余生分开走 2020-11-22 16:35

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

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


        
相关标签:
15条回答
  • 2020-11-22 17:25

    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*/
    }
    
    0 讨论(0)
  • 2020-11-22 17:26

    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()
                }
    
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-11-22 17:27

    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

    0 讨论(0)
  • 2020-11-22 17:29

    Update for swift 5

    Serial Queue

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

    Concurrent Queue

    let concurrentQueue = DispatchQueue.init(label: "concurrentQueue", qos: .background, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil)
    
    concurrentQueue.async {
    // code to execute
    }
    

    From Apple documentation:

    Parameters

    label

    A string label to attach to the queue to uniquely identify it in debugging tools such as Instruments, sample, stackshots, and crash reports. Because applications, libraries, and frameworks can all create their own dispatch queues, a reverse-DNS naming style (com.example.myqueue) is recommended. This parameter is optional and can be NULL.

    qos

    The quality-of-service level to associate with the queue. This value determines the priority at which the system schedules tasks for execution. For a list of possible values, see DispatchQoS.QoSClass.

    attributes

    The attributes to associate with the queue. Include the concurrent attribute to create a dispatch queue that executes tasks concurrently. If you omit that attribute, the dispatch queue executes tasks serially.

    autoreleaseFrequency

    The frequency with which to autorelease objects created by the blocks that the queue schedules. For a list of possible values, see DispatchQueue.AutoreleaseFrequency.

    target

    The target queue on which to execute blocks. Specify DISPATCH_TARGET_QUEUE_DEFAULT if you want the system to provide a queue that is appropriate for the current object.

    0 讨论(0)
  • 2020-11-22 17:29
       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.

    0 讨论(0)
  • 2020-11-22 17:34

    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 utility queue - for network query, does not wait for the result, it is a concurrent queue, the block (usually) does not wait when started. Exception for a concurrent queue could be, when its task limit has been previously reached, then the queue temporarily turns into a serial queue and waits until some previous task in that queue completes.

    async main queue - for touching the UI, the block does not wait for the result, but waits for its slot at the start. The main queue is a serial queue.

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

    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
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题