介绍 Introduction

Concurrency is a concept that every mobile developer should know. It is the notion of multiple things happening at the same time.

并发是每个移动开发人员都应了解的概念。 这是同时发生多件事的概念

The key is to divide our program into small tasks that can run in parallel, and the final result shouldn’t be affected by the order of the task completion, meaning if task A finishes before task B, the outcome should be the same as if task B finishes before task A.

关键是将程序划分为可以并行运行的小任务,并且最终结果不应受任务完成顺序的影响,这意味着,如果任务A在任务B之前完成,则结果应与任务B在任务A之前完成。

In the iOS ecosystem, there are several tools to achieve that:

在iOS生态系统中,有几种工具可以实现这一目标:

  • NSOperation NSO操作
  • NSThread NSThread
  • Grand Central Dispatcher 大中央调度员
  • Reactive Programming frameworks like RxSwift, ReactiveSwift, Combine, etc 响应式编程框架,例如RxSwift,ReactiveSwift,Combin等

When dealing with network requests, the recommended approach is to have an asynchronous task (the thread initiated the task won’t wait until the task is completed to continue executing other tasks) in a background thread (because the main thread should be free for UI updates only). This will guarantee a smooth, freeze-free user experience, that allows the user to continue using the app while the network request eventually finishes some time in the future.

处理网络请求时,推荐的方法是在后台线程中有一个异步任务 (启动该任务的线程将等到该任务完成后再继续执行其他任务)(因为主线程应可用于UI)仅更新)。 这将确保流畅,无冻结的用户体验,使用户可以继续使用应用程序,同时网络请求最终会在将来的某个时间结束。

Parallel execution improves the overall speed of the app, if task A takes 2 seconds and task B takes 3 seconds, the 2 tasks running in parallel would take 3 seconds, whereas running in serial (one after the other) would take 5 seconds.

并行执行可提高应用程序的整体速度,如果任务A花费2秒,任务B花费3秒,则并行运行的2个任务将花费3秒,而串行运行(一个接一个)将花费5秒。