How to make a task sleep 如何使任务进入休眠状态

How to make a task sleep 如何使任务进入休眠状态

温馨提示:本文最后更新于2025-02-08 12:08:22,某些文章具有时效性,若有错误或已失效,请在下方留言

Swift’s Task struct has a static sleep() method that will cause the current task to be suspended for a set period of time. You need to call Task.sleep() using await as it will cause the task to be suspended, and you also need to use try because sleep() will wake and throw an error if the task is cancelled.
Swift 的 Task 结构体有一个静态的 sleep() 方法,它会导致当前任务暂停一段时间。您需要使用 await 调用 Task.sleep(),因为它会导致任务暂停,并且您还需要使用 try,因为如果任务被取消,sleep() 将唤醒并引发错误。

For example, this will make the current task sleep for at least 3 seconds:
例如,这将使当前任务休眠至少 3 秒:

try await Task.sleep(for: .seconds(3))

Calling Task.sleep() will make the current task sleep for at least the amount of time you ask, not exactly the time you ask. There is a little drift involved because the system might be busy doing other work when the sleep ends, but you are at least guaranteed it won’t end before your time has elapsed.
调用 Task.sleep() 将使当前任务至少休眠你要求的时间,而不是你 要求的 时间。这涉及到一点偏差,因为当睡眠结束时,系统可能正忙于执行其他工作,但您至少可以保证它不会在您的时间过去 之前 结束。

If you’re happy to add a little extra drift, you can add a tolerance parameter that allows the task to sleep for longer if needed. So, this might sleep for three seconds up to a total of four seconds:
如果您愿意添加一点额外的偏差,则可以添加一个 tolerance 参数,该参数允许任务在需要时休眠更长时间。因此,这可能会休眠 3 秒,最多持续 4 秒:

try await Task.sleep(for: .seconds(3), tolerance: .seconds(1))

Swift’s Task.sleep() method automatically checks for cancellation, meaning that if you cancel a sleeping task it will be woken and throw a CancellationError for you to catch.
Swift 的 Task.sleep() 方法会自动检查是否取消,这意味着如果你取消了一个休眠任务,它将被唤醒并抛出一个 CancellationError 供你捕获。

Tip: Unlike making a thread sleep, Task.sleep() does not block the underlying thread, allowing it pick up work from elsewhere if needed.
提示: 与使线程休眠不同,Task.sleep() 不会 阻塞底层线程,允许它在需要时从其他位置获取工作。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享