本文介绍了我可以在semaphore.wait()主线程上调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种方法可以给我照片验证身份.

I have a method which gives me photo auth status.

func photosAuthorizationStatus() -> PHAuthorizationStatus {
        var authStatus = PHAuthorizationStatus.notDetermined
        let semaphore = DispatchSemaphore(value: 0)
        PHPhotoLibrary.requestAuthorization { (status: PHAuthorizationStatus) in
            authStatus = status
            semaphore.signal()
        }
        semaphore.wait()
        return authStatus
    }

我在ViewController的viewDidAppear中调用此方法,但应用程序未冻结.

I am calling this method in viewDidAppear of a ViewController , but Application is not freezing.

但是如果我明确要求mainQueue时调用semaphore.wait,应用程序将冻结.

But if I call semaphore.wait when I ask mainQueue explicitly Application is freezing.

DispatchQueue.main.async{
let semaphore = DispatchSemaphore(value: 0)
semaphore.wait()

}

//上面的代码将冻结应用程序.

// Above code will freeze the application.

我能知道原因吗?

推荐答案

在标题中,您要求:

您应避免由于任何原因阻塞主线程.是否wait用于信号量或调度组,甚至用于同步调度(例如,> c1> )超过几毫秒的任何时间.如果您在错误的时间执行看门狗进程,则有可能会杀死您的应用程序,这会导致可怕的用户体验.

You should avoid blocking the main thread for any reason. Whether wait for semaphores or dispatch groups, or even synchronously dispatching (e.g., sync) of anything more than a few milliseconds. You risk having the watchdog process kill your app if you do this at the wrong time, and it results in a horrible UX.

然后您继续问:

DispatchQueue.main.async {
   let semaphore = DispatchSemaphore(value: 0)
   semaphore.wait()
}

以上代码将冻结应用程序.

Above code will freeze the application.

我能知道原因

该代码显示为阻止主线程在此信号量上等待signal".因此,在signal到达之前,主线程将被阻塞.但是绝不应该阻塞主线程,因为它会在死锁主线程时提供服务,其中包括UI和应用程序将冻结.

That code says "block the main thread waiting for a signal on this semaphore". So, until that signal arrives, the main thread will be blocked. But the main thread should never be blocked because it services, amongst other things, the UI, and your app will freeze if you deadlock the main thread.

底线,切勿阻塞主线程.

Bottom line, never block the main thread.

这篇关于我可以在semaphore.wait()主线程上调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 03:36