在异步派发给它之前是否需要检查当前线程是否是主线程?

Is it necessary to check whether the current thread is the main thread or not before dispatching to it asynchronously?

真的有必要在异步派发之前检查当前线程是否为主线程吗?在性能或其他方面有什么优势吗?

我知道从同一个队列同步调度会导致死锁。但是我真的需要像下面代码段中的人那样检查当前线程吗?

+ (void)dispatchOnMainThread:(void (^)(void))task
    {
        if ([NSThread isMainThread]) // Is this necessary?
        {
            task();
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), task);
        }
    }

But do i really need to check the current Thread like someone did in the following Snippet

不是真的。如果你已经在主线程上,那么当你的代码结束时,你的 dispatch_async 块将被分派。所以可能会有轻微的延迟,因为我们需要当前的 运行 循环/交易结束,但不会引人注意。

我一直使用 dispatch_async 到主线程,以确保在我不确定的情况下(例如 KVO 回调)我在主线程上。没有伤害,没有犯规。这只是一种保险。

不需要检查是否在主线程,dispatch_async只是将任务放入队列returns。万无一失。

另一方面,如果你检查你是否在主线程上并直接执行任务,那么不要调用你的方法dispatchOnMainThread,因为它不调度。应用程序行为可能因此而改变。我将其称为 runOnMainThread,并将其设为普通 C 函数。而且它更适合调试。