[英]Swift: can I use async/await syntax with a function that already returns synchronously a value?
I know that I can use async/await to replace this:我知道我可以使用 async/await 来替换它:
func test(_ completion: @escaping (Int) -> Void) {
// ...
completion(foundValue)
}
with this:有了这个:
func test async -> Int {
let result = await calculate()
return result
}
However, can I do something if the initial function is like this?但是,如果最初的 function 是这样的,我可以做些什么吗?
func test(_ completion: @escaping (Int) -> Void) -> Int {
// ...
}
Thank you for your help谢谢您的帮助
If your function doesn't need to wait for completion handler call then you can create a top level task and call your completion handler from the task after doing asynchronous work:如果您的 function 不需要等待完成处理程序调用,那么您可以创建一个顶级任务并在执行异步工作后从任务中调用您的完成处理程序:
func test(_ completion: @escaping (Int) -> Void) -> Int {
// synhronous calls
Task {
// async funtion calls
completion(value)
}
return value
}
If you need to wait for all your asynchronous task completion before returning, you can use a semaphore for that:如果您需要在返回之前等待所有异步任务完成,您可以使用信号量:
func test(_ completion: @escaping (Int) -> Void) -> Int {
let semaphore = DispatchSemaphore(value: 0)
// synhronous calls
Task {
// async funtion calls
completion(value)
// signal async task completion
semaphore.signal()
}
// wait for async task completion
semaphore.wait()
return value
}
Note that using semaphore.wait()
blocks the current thread and blocking the thread can cause undefined runtime behaviors in modern concurrency.请注意,使用
semaphore.wait()
会阻塞当前线程,并且阻塞线程会导致现代并发中未定义的运行时行为。 So proceed with caution when using such approach.因此,在使用这种方法时要谨慎行事。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.