函数
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:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。