Search code examples
swiftgrand-central-dispatchnsoperationqueue

Application is crashing while using DispatchQueue.main.sync


I am doing experiments with Grand Central Dispatch and have come across a crash on synchronous task.

func viewDidLoad() {
    super.viewDidLoad()

    self.testHello()
    print("Task2")
}

func testHello() {
    DispatchQueue.main.sync {
        print("Task1")
    }
}

Upon execution of above given function, I am facing crash.

Explanation on above crash will be appreciated.


Solution

  • From DispatchQueue.sync documentation:

    ...this function does not return until the block has finished. Calling this function and targeting the current queue results in deadlock.

    You are already on the main queue and you are forcing code to be executed synchronously on the main queue. The fact that you are on the main queue means that no other code can be executed on the queue right now, however, sync waits until that code is executed, therefore you are deadlocking the queue and you whole app.