函數
with
withTaskGroup(of:returning:body:)
啟動一個可以包含動態數量的子任務的新範圍。
聲明
func withTaskGroup<ChildTaskResult, GroupResult>(
of childTaskResultType: ChildTaskResult.Type,
returning returnType: GroupResult.Type = GroupResult.self,
body: (inout TaskGroup<ChildTaskResult>) async -> GroupResult
) async -> GroupResult where ChildTaskResult : Sendable
詳述
一個組在返回之前等待其所有子任務完成或被取消。此函數返回後,任務組始終為空。
要收集組子任務的結果,可以使用for
- await
- in
循環:
var sum = 0
for await result in group {
sum += result
}
如果您需要更多控製或隻需要幾個結果,您可以直接調用next()
:
guard let first = await group.next() else {
group.cancelAll()
return 0
}
let second = await group.next() ?? 0
group.cancelAll()
return first + second
任務組取消
您可以通過在任務組上調用cancellAll()
方法或取消正在運行該組的任務來取消任務組及其所有子任務。
如果您調用async(priority:operation:)
在已取消的組中創建新任務,則該任務在創建後立即取消。或者,您可以調用 asyncUnlessCancelled(priority:operation:)
,如果組已被取消,它不會創建任務 在這兩個函數之間進行選擇可以讓您控製如何對組內的取消做出反應:一些子任務需要運行而不管取消,但是當你知道它們不能產生有用的結果時,最好不要創建其他任務。
由於使用此方法添加到組的任務是非拋出的,因此這些任務無法通過拋出 CancellationError
來響應取消。任務必須以其他方式處理取消,例如返回到目前為止已完成的工作、返回空結果或返回 nil
。對於需要通過拋出錯誤來處理取消的任務,請改用withThrowingTaskGroup(of:returning:body:)
方法。
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift withThrowingTaskGroup(of:returning:body:)用法及代碼示例
- Swift withoutActuallyEscaping(_:do:)用法及代碼示例
- Swift KeyValuePairs flatMap(_:)用法及代碼示例
- Swift String.UTF8View first用法及代碼示例
- Swift Result.Publisher zip(_:_:_:)用法及代碼示例
- Swift Optional.Publisher reduce(_:_:)用法及代碼示例
- Swift Int8 ~(_:)用法及代碼示例
- Swift SetAlgebra isStrictSubset(of:)用法及代碼示例
- Swift UInt +(_:)用法及代碼示例
- Swift Array enumerated()用法及代碼示例
- Swift FlattenSequence prefix(_:)用法及代碼示例
- Swift Slice endIndex用法及代碼示例
- Swift LazySequence split(maxSplits:omittingEmptySubsequences:whereSeparator:)用法及代碼示例
- Swift MutableCollection partition(by:)用法及代碼示例
- Swift ReversedCollection min(by:)用法及代碼示例
- Swift RandomNumberGenerator用法及代碼示例
- Swift Dictionary.Keys shuffled()用法及代碼示例
- Swift AnySequence elementsEqual(_:)用法及代碼示例
- Swift UInt &<<(_:_:)用法及代碼示例
- Swift Optional.Publisher tryDrop(while:)用法及代碼示例
- Swift DefaultIndices endIndex用法及代碼示例
- Swift Substring.UnicodeScalarView insert(contentsOf:at:)用法及代碼示例
- Swift LazyFilterSequence dropFirst(_:)用法及代碼示例
- Swift LazySequence suffix(from:)用法及代碼示例
- Swift ArraySlice starts(with:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 withTaskGroup(of:returning:body:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。