简体   繁体   中英

Which is better, dispatching NSNotification on the main thread or handing the notification on the main thread

I understand that there may not be a right answer, but I was very curious to find out what people think about this issue or if there are pros and cons for the following approaches. First example dispatches the notification on the main thread and second example handles notification in the main thread. If you were to choose one of the two approaches, which one and why?

dispatch_async(dispatch_get_main_queue(), ^{
   [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName"
                                                       object:nil];
}); 


- (void)handleNotification:(NSNotification *)notification {
   dispatch_async(dispatch_get_main_queue(), ^{
       [self updateUI];
   });
}

It makes sense to dispatch the notification on the main thread if you know that some of the handlers need to deal with UI elements. However, if there are multiple notification post sites, then this becomes a potential bug prone thing. I would rather want to dispatch to the main thread in the notification handler, so that each handler has a complete control over this.

I appreciate any feedback you have.

I would prefer the second approach, where the sender is also using the current execution context. This is more efficient. Dispatching unnecessarily on the main thread should be avoided. It should be clearly documented, though.

The receiver, on the other hand, is the only instance knowing if there are any constraints for its code regarding the execution context. That is, if there is none, it can just use the current execution context. Otherwise, it should dispatch to whatever thread/queue which is required for the code.

So, we certainly agree ;)

Use the modern block-based syntax for adding notification observers, which allows you to specify a queue for the code to be run on when the notification is received.

Specifying at the listener end is the way to go - you can post notifications from anywhere, on any thread. Only the listener knows if it matters what thread code runs on.

发布通知将同步。更好地保持代码简单。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM