简体   繁体   中英

Whether those two ways of dispatching work to main thread (CGD and NSOperationQueue) are equivalent?

I'm curious whether those two types to dispatch work to main queue are equivalent or maybe there are some differentials?

 dispatch_async(dispatch_get_main_queue()) {
        // Do stuff...
    }

and

NSOperationQueue.mainQueue().addOperationWithBlock { [weak self] () -> Void in
       // Do stuff..
    }

There are differences, but they are somewhat subtle.

Operations enqueued to -[NSOperationQueue mainQueue] get executed one operation per pass of the run loop. This means, among other things, that there will be a "draw" pass between operations.

With dispatch_async(dispatch_get_main_queue(),...) and -[performSelectorOnMainThread:...] all enqueued blocks/selectors are called one after the other without spinning the run loop (ie allowing views to draw or anything like that). The runloop will continue after executing all enqueued blocks.

So, with respect to drawing, dispatch_async(dispatch_get_main_queue(),...) and -[performSelectorOnMainThread:...] batch operations into one draw pass, whereas -[NSOperationQueue mainQueue] will draw after each operation.

For a full, in-depth investigation of this, see my answer over here .

At a very basic level they are not both the same thing.

Yes, the operation queue method will be scheduled on GCD queue. But it also gets all the rich benefits of using operation queues, such as an easy way to add dependent operations; state observation; the ability to cancel an operation…

So no, they are not equivalent.

Yes there are difference in GCD and NSOperation.
GCD is light weight can be used to give flavor of multithreading like loading profile pic, loading web page, network call that surely returns at earliest.

NSOperation queue
1. Usually used to make heavy network calls, sort thousand's of record etc.
2. Can add new operation, delete, get current status at any operation
3. Add completion handler
4. get operation count etc

are added advantages over GCD

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