我在SWIFT中有一个缓慢的阻塞函数,我想以非阻塞(异步/等待)的方式调用它.
以下是原始的阻止代码:
// Original
func totalSizeBytesBlocking() -> UInt64 {
var total: UInt64 = 0
for resource in slowBlockingFunctionToGetResources() {
total += resource.fileSize
}
return total
}
以下是我让它成为非阻塞的try :
// Attempt at async/await
func totalSizeBytesAsync() async -> UInt64 {
// I believe I need Task.detached instead of just Task.init to avoid blocking the main thread?
let handle = Task.detached {
return self.slowBlockingFunctionToGetResources()
}
// is this the right way to handle cancellation propagation with a detached Task?
// or should I be using Task.withTaskCancellationHandler?
if Task.isCancelled {
handle.cancel()
}
let resources = await handle.value
var total: UInt64 = 0
for resource in resources {
total += resource.fileSize
}
return total
}
我的目标是能够等待来自主参与者/线程的异步版本,并让它在后台线程上执行缓慢的阻塞工作,同时继续更新主线程上的UI.
这应该怎么做呢?