comparison GCD vs. performSelectorInBackground: dispatch_async not in background

后端 未结 1 1382
你的背包
你的背包 2021-01-31 23:57

Grand Central Dispatch is great and reduces the amount of code but why I cannot run something on a background thread?
I have made a sample application to show what I mean (n

1条回答
  •  再見小時候
    2021-02-01 00:04

    UIKit classes should be used only from an application’s main thread. (From iOS4, drawing to a graphics context is thread-safe.) You can't use UIKit stuff in a background thread.

    Thus, you can only use dispatch_async(dispatch_get_main_queue(), block) in this situation.

    dispatch_async(dispatch_get_main_queue(), ^(void) {
    

    It will invoke the block on the main thread in the runloop of the main thread.

    dispatch_async(dispatch_queue_create("myGCDqueue", NULL), ^(void) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
    

    It will invoke the block in a background thread. You can't use it because you want to use UIKit in the block. And be careful dispatch_async(dispatch_queue_create(, it might cause memory leak, you have to release the serial queue that is created by dispatch_queue_create.

    dispatch_sync(dispatch_queue_create("myGCDqueue", NULL), ^(void) {
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
    

    dispatch_sync waits until the block is done.

    dispatch_sync(dispatch_get_main_queue(), ^(void) {
    

    It causes DEADLOCK.

    0 讨论(0)
提交回复
热议问题