Difference between DispatchQueue types in swift

后端 未结 2 740
谎友^
谎友^ 2021-02-11 00:55

As I understand there are 3 types of DispatchQueue in swift:

  • Main (serial) (Main Thread)
  • Global (Concurrent) (Background
2条回答
  •  礼貌的吻别
    2021-02-11 01:51

    DispatchQueue's do not correspond to a single thread directly. The only restriction is that you are only allowed to access the UI from the main thread, which can be done through DispatchQueue.main. However, there's no guarantee that the system will dispatch your execution block to a specific thread if you call it on a specific queue.

    DispatchQueue.async is a non-blocking operation, so you can execute several code blocks asynchronously on the same queue without blocking a specific thread, this is why you should always dispatch operations to the main queue asynchronously, to avoid blocking UI updates, since the main queue is solely responsible for UI related tasks. Calling async on any queue, does not guarantee that the execute will happen on a specific thread (be it background or main), it only guarantees that the operation will be executed in a non-blocking manner.

    DispatchQueue.sync is a blocking operation, meaning that while a single sync code block is being executed, no other piece of code can be executed on the specific DispatchQueue, so if you dispatch a code block to the main queue synchronously, you will block UI updates and hence your app will freeze.

提交回复
热议问题