函數
with
withThrowingTaskGroup(of:returning:body:)
啟動一個可以包含動態數量的拋出子任務的新範圍。
聲明
func withThrowingTaskGroup<ChildTaskResult, GroupResult>(
of childTaskResultType: ChildTaskResult.Type,
returning returnType: GroupResult.Type = GroupResult.self,
body: (inout ThrowingTaskGroup<ChildTaskResult, Error>) async throws -> GroupResult
) async rethrows -> 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:)
,如果組已被取消,它不會創建任務 在這兩個函數之間進行選擇可以讓您控製如何對組內的取消做出反應:一些子任務需要運行而不管取消,但是當你知道它們不能產生有用的結果時,最好不要創建其他任務。
在任務組的一項任務中拋出錯誤不會立即取消該組中的其他任務。但是,如果您在任務組中調用 next()
並傳播其錯誤,則會取消所有其他任務。例如,在下麵的代碼中,沒有取消任何內容,並且組不會拋出錯誤:
withThrowingTaskGroup { group in
group.addTask { throw SomeError() }
}
相比之下,此示例拋出 SomeError
並取消組中的所有任務:
withThrowingTaskGroup { group in
group.addTask { throw SomeError() }
try group.next()
}
單個任務在對 Group.next()
的相應調用中拋出其錯誤,這使您有機會處理單個錯誤或讓組重新拋出錯誤。
可用版本
iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+
相關用法
- Swift withTaskGroup(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大神的英文原創作品 withThrowingTaskGroup(of:returning:body:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。