skip to Main Content

why lable’s text can’t change, but can debug str?
i know queue.sync is excute in main thread,when i sleep in main thread。

class ViewController: UIViewController {
    
    let queue = DispatchQueue(label: "queue", qos: .userInteractive)
    let sem = DispatchSemaphore(value: 0)

    @IBOutlet var label: UILabel!
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        for _ in 0..<10 {
            queue.sync {
                Thread.sleep(forTimeInterval: 2)
                let str = String(Int.random(in: 1...10))
                debugPrint(str)
                DispatchQueue.main.async {
                    self.label.text = str
                }
            }
        }
        
    }
}

2

Answers


  1. You are blocking yourself. Consider:

    queue.sync { // 1
        Thread.sleep(forTimeInterval: 2)
        DispatchQueue.main.async { // 2
             // *
        }
    }
    
    1. You say queue.sync while on the main thread. So now the main thread is blocking waiting for queue to finish; no code can run on the main thread.
    2. You then say DispatchQueue.main.async, asking for the closure (*) to be performed on the main thread. But that, as we have just said, is impossible; the main thread is blocking, and no code can run on it.

    As for your debugPrint, it is on queue, not the main thread, so no problem.

    (Note: everything you’re doing is illegal. Never block the main thread, and never sleep.)

    Login or Signup to reply.
  2. you are blocking with waiting the main thread for queue to finish the task. So updating label text code not running on main thread. That’s by its not updating.

    Try with async method that will not block the main thread.

    queue.async {
                    Thread.sleep(forTimeInterval: 2)
                    let str = String(Int.random(in: 1...10))
                    debugPrint(str)
                    DispatchQueue.main.async {
                        self.label.text = str
                    }
                }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search