1

I find that in some cases, the result that I perform [self doSomething] directly is different from that I perform in the block of a GCD body like this:

dispatch_async(dispatch_get_main_queue(), ^{

    [self doSomething]

}) 

I have perform [NSThread currentThread] to confirm it has already been on the main thread. So what is the difference?

wkx
  • 431
  • 1
  • 4
  • 7
  • The above will dispatch it on the main thread `asynchonously` on the next run cycle. Calling a function will block the current thread until it completes. – Brandon Jun 04 '16 at 16:07
  • 2
    The intent of asynchronously dispatching something to the main queue while already on the main thread is merely to let finish whatever is currently running on the main thread. IMHO, it is often a code smell for some deeper design issue. You'll see this when the developer is in the middle of some event handler and wants to initiate the next task, but it would cause problems if it started it immediately, so they'll dispatch it back to the main queue. If you share in what context you saw this pattern, we can comment further. – Rob Jun 04 '16 at 16:34

1 Answers1

2

Only [self doSomething] will be synchronized call and using dispatch_async will be asynchronized call.

Statement A
[self doSomething]
Statement B

Above code will start executing Statement A, finish Statement A, Start executing function doSomething, finish function doSomething and then start executing and finish Statement B.

Statement A
dispatch_async(dispatch_get_main_queue(), ^{
    [self doSomething]
})
Statement B

Above block will start and finish execution of Statement A, then it adds doSomething function call in the queue (it may or may not start immediately) then it will start execution of Statement B without waiting to finish execution of function doSomething.

So, if Statement B (and other statements which are after your function call) is independent of result of function doSomething, then you can do async call.

Hardik
  • 139
  • 1
  • 10
  • So is it hard to know whether doSth or Statement B will execute first on the second condition? – wkx Jun 11 '16 at 14:58
  • @wkx, yes, it is hard to know which statement will complete execution first for second condition. – Hardik Jun 12 '16 at 21:48