Код: Выделить всё
class SocketClass {
private var pollingTask: Task?
func startPoll() {
// Stop previous polling task
pollingTask?.cancel()
pollingTask = nil
pollingTask = Task {
while !Task.isCancelled {
// Send ping
// Wait for pong timeout
await self.waitForPong()
// Wait for the next ping interval
try? await Task.sleep(nanoseconds: UInt64(30_000_000_000))
}
}
// Is it possible that at this point that there are two tasks
// attempting to poll before the previous one heard it needed to cancel?
}
private func waitForPong(_ uuid: UUID, _ count: Int) async -> Bool {
let pongReceived = await withCheckedContinuation { continuation in
socket.once("pong") { [weak self] _, _ in
continuation.resume(returning: true)
}
}
return pongReceived
}
}
Но при таком коде нет никаких гарантий, что может наступить момент где две задачи опроса работают одновременно, хотя бы немного, верно? Особенно, если код пинг-понга не проверяет, отменено ли задание.
Подробнее здесь: https://stackoverflow.com/questions/792 ... time-is-it
Мобильная версия