swift中DispatchGroup,可以分組管理異步任務(wù);
1.分組管理多個(gè)異步任務(wù)
func dispatchGroupConcurrentTest() {
print("class:\(type(of: self)),line:\(#line)")
let WORKMAXNUM = 10
let dispatchGroup = Dispatch.DispatchGroup()
let queue1 = DispatchQueue(label: "1")
let queue2 = DispatchQueue(label: "2")
let queue3 = DispatchQueue(label: "3")
queue1.async(group: dispatchGroup, execute:DispatchWorkItem {
for i in 0..<WORKMAXNUM {
print("\(i) execute")
}
} )
queue2.async(group: dispatchGroup, execute:DispatchWorkItem {
for i in 0..<WORKMAXNUM {
print("\(i + 10) execute")
}
} )
queue3.async(group: dispatchGroup, execute:DispatchWorkItem {
for i in 0..<WORKMAXNUM {
print("\(i + 20) execute")
}
} )
dispatchGroup.notify(queue: DispatchQueue.main) {
print("main queue execute!")
}
}
執(zhí)行結(jié)果
class:ViewController,line:19
0 execute
1 execute
2 execute
3 execute
4 execute
5 execute
6 execute
7 execute
8 execute
9 execute
10 execute
20 execute
11 execute
12 execute
13 execute
14 execute
15 execute
16 execute
21 execute
17 execute
22 execute
23 execute
24 execute
25 execute
26 execute
27 execute
18 execute
28 execute
29 execute
19 execute
main queue execute!
2.分組管理多個(gè)串行的異步任務(wù)
func dispatchGroupSerialTest() {
print("class:\(type(of: self)),line:\(#line)")
let WORKMAXNUM = 10
let dispatchGroup = Dispatch.DispatchGroup()
let queue1 = DispatchQueue(label: "1")
let queue2 = DispatchQueue(label: "2")
let queue3 = DispatchQueue(label: "3")
dispatchGroup.enter()
queue1.async(group: dispatchGroup, execute:DispatchWorkItem {
for i in 0..<WORKMAXNUM {
print("\(i) execute")
}
dispatchGroup.leave()
} )
print("before wait")
dispatchGroup.wait()
print("end wait")
dispatchGroup.enter()
queue2.async(group: dispatchGroup, execute:DispatchWorkItem {
for i in 0..<WORKMAXNUM {
print("\(i + 10) execute")
}
dispatchGroup.leave()
} )
print("before wait")
dispatchGroup.wait()
print("end wait")
dispatchGroup.enter()
queue3.async(group: dispatchGroup, execute:DispatchWorkItem {
for i in 0..<WORKMAXNUM {
print("\(i + 20) execute")
}
dispatchGroup.leave()
} )
dispatchGroup.notify(queue: DispatchQueue.main) {
print("main queue execute!")
}
}
執(zhí)行結(jié)果
class:ViewController,line:57
before wait
0 execute
1 execute
2 execute
3 execute
4 execute
5 execute
6 execute
7 execute
8 execute
9 execute
end wait
before wait
10 execute
11 execute
12 execute
13 execute
14 execute
15 execute
16 execute
17 execute
18 execute
19 execute
end wait
20 execute
21 execute
22 execute
23 execute
24 execute
25 execute
26 execute
27 execute
28 execute
29 execute
main queue execute!
3.小結(jié)
- 1.注意上述兩種不同的使用場(chǎng)景。
- 2.注意DispatchGroup的enter和leave配對(duì)使用浓体,以及與wait的配合使用砰左。