一个 Swift 实用工具,为使用 Swift 5.5 中引入的新的 async/await 语法的异步操作提供超时机制。
actor
和 TaskGroup
timeout
错误。AsyncTimeout
结构体集成到您的项目中。withTimeout
包装您想要设置超时的异步操作。将以下内容添加到您的 Package.swift 依赖项中
dependencies: [
.package(url: "https://github.com/RayKitajima/AsyncTimeout.git", from: "1.0.0"),
],
import AsyncTimeout
do {
let result: YourReturnType = try await AsyncTimeout.withTimeout(seconds: 5) {
return try await someAsyncFunc()
}
} catch AsyncTimeout.CustomError.timeout {
print("The operation timed out!")
} catch {
print("An error occurred: \(error.localizedDescription)")
}
AsyncTimeout
:包含超时逻辑的主要结构体。OperationState
:一个 actor,用于跟踪操作是否已完成。它用于安全地处理潜在的并发代码中的状态。CustomError
:一个枚举,具有一个 timeout
case,表示超时错误。withTimeout(seconds:operation:)
:此函数接受超时间隔(以秒为单位)和一个异步操作。如果操作未在给定的超时时间内完成,它将抛出一个超时错误。result!
)。 务必确保操作不会导致 nil 值,否则将会崩溃。