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