[Swift实际操作]七、常见概念-(12)使用DispatchGroup(调度组)管理线程数组

本文将为你演示调度组的使用,使用调度组可以将多个线程中的人物进行组合管理,
可以设置当多个相同层次的任务完成之后,再执行另一项任务。

首先导入需要使用的界面工具框架

import UIKit

在控制台输出一条日志语句,表示调试任务开始执行

print("Start the task and display teh Loading animation.")

接着初始化一个调度组对象。

let gro =DispatchGroup()

同时运行多个任务,
每个任务的启动时间是按照加入队列的顺序,
结束的顺序则依赖各自具体的任务。

let globalQueue = DispatchQueue.global()

通过队列的异步方法,将传入的block块,放入指定的queue队列里运行。

1 globalQueue.async(group: gro, 
2                   excute: DispatchWorkItem(block:{print("Load a user picture from the remote server.")}))

使用相同的方式,将另外一个异步执行的线程任务,添加到队列中。

1 globalQueue.async(group: gro, 
2                   excute: DispatchWorkItem(block:{print("Get the annual record of all transactions by user id.")}))

当调度组中的任务全部完成后,调用通知方法,完成调度组的任务,并执行接下来的块中的动作。

1 gro.notify(queue: globalQueue, 
2            execute:{print("Complete all tasks and hide the Loading animation.")})

再次将第三个异步执行的线程任务,添加到队列中。
然后点击底部的显示控制台按钮图标,打开控制台。

1 globalQueue.async(group: gro, 
2                   excute: DispatchWorkItem(block:{print("Get the collection of goods by user id.")}))

技巧:1.使用快捷键Command+Shift+O,可以通过键入关键词的方式,快速切换至某个文件。
           2.下载Xcode尽量别用迅雷,迅雷有可能会提供包含后门的Xcode

原文地址:https://www.cnblogs.com/strengthen/p/9780209.html