Asynchronous DispatchSemaphore.wait(timeout:) Task handle alternative

535 Views Asked by At

I'm currently looking for a Task based alternative for my code using DispatchSemaphore:

func checkForEvents() -> Bool
    let eventSemaphore = DispatchSemaphore(value: 0)
    eventService.onEvent = { _ in
        eventSemaphore.signal()
    }
        
    let result = eventSemaphore.wait(timeout: .now() + 10)
    guard result == .timedOut else {
        return true
    }
    return false
}

I'm trying to detect if any callback events happen in a 10-second time window. This event could happen multiple times, but I only want to know if it occurs once. While the code works fine, I had to convert the enclosing function to async which now shows this warning:

Instance method 'wait' is unavailable from asynchronous contexts; Await a Task handle instead; this is an error in Swift 6`

I'm pretty sure this warning is kind of wrong here since there's no suspension point in this context, but I would still like to know what's the suggested approach in Swift 6 then. I couldn't find anything about this "await a Task handle" so the closest I've got is this:

func checkForEvents() async -> Bool {
    var didEventOccur = false
    eventService.onEvent = { _ in
        didEventOccur = true
    }
    try? await Task.sleep(nanoseconds: 10 * 1_000_000_000)
    return didEventOccur
}

But I can't figure out a way to stop sleeping early if an event occurs...

0

There are 0 best solutions below