在哪个线程中调用iOS完成处理程序块?

时间:2021-12-31 21:00:42

For example, in GKScore's reportScoreWithCompletionHandler (documentation), suppose you call

例如,在GKScore的reportScoreWithCompletionHandler(文档)中,假设您调用

[score reportScoreWithCompletionHandler:^(NSError *error) {
   // do some stuff that may be thread-unsafe
}];

In which thread will the completion handler be called: the main thread, the same thread as reportScoreWithCompletionHandler was called, or a different thread (presumably the thread that the actual score reporting is done)?

在哪个线程中将调用完成处理程序:主线程,与reportScoreWithCompletionHandler相同的线程被调用,或者是一个不同的线程(可能是实际得分报告完成的线程)?

In other words, does the work done in the completion handler need to be thread-safe (as in, it doesn't matter what thread it's done in)?

换句话说,在完成处理程序中完成的工作是否需要是线程安全的(例如,它在哪个线程中完成并不重要)?

1 个解决方案

#1


6  

In practical terms it doesn't matter.

实际上并不重要。

If you need your completion to run in the main thread, just dispatch it to the main thread:

如果您需要在主线程中运行完成,只需将其发送到主线程:

[score reportScoreWithCompletionHandler:^(NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        // do your stuff here
    });
}];

#1


6  

In practical terms it doesn't matter.

实际上并不重要。

If you need your completion to run in the main thread, just dispatch it to the main thread:

如果您需要在主线程中运行完成,只需将其发送到主线程:

[score reportScoreWithCompletionHandler:^(NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        // do your stuff here
    });
}];