Is it possible to access result of async function outside of task on background thread? We can access result from task on main thread using @MainActor But I need it on background thread which is actually waiting for the result of async func.
Consider following code:
func asyncFunc() async -> Int {
// some async code here
}
// This func is running on BG thread
func syncFunc() -> Int {
let semaphore = DispatchSemaphore(value: 0)
var value: Int
Task {
value = await asyncFunc() // Produces “Mutation of captured var 'value' in concurrently-executing code” error
semaphore.signal()
}
semaphore.wait()
return value
}
For this compiler shows error for the first line in Task:
Mutation of captured var 'value' in concurrently-executing code.
And yes, this error is clear and expected. Then I try to use Actor to wrap value:
actor ValueActor {
var value = 0
func setValue(_ newValue: Int) {
value = newValue
}
}
// This func is running on BG thread
func syncFunc() -> Int {
let semaphore = DispatchSemaphore(value: 0)
let valueActor = ValueActor()
Task {
let value = await asyncFunc()
await valueActor.setValue(value)
semaphore.signal()
}
semaphore.wait()
return valueActor.value // Produces “Actor-isolated property 'value' can not be referenced from a non-isolated context” error
}
In this case, the error is for the returning value:
Actor-isolated property 'value' can not be referenced from a non-isolated context
This error is also expected, but... may be some workaround can be found to return the value?