Swift UI blocking

,

I have an Swift App that calls a C function. I have to add a sleep in the C code which causes UI blocking. Is there any way to prevent UI blocking with this design?.:
Swift Button calls a C function
C function is semaphore, mutex protected. Add in Sleep causes UI blocking. Sleep exits, functions returns, UI blocking released.

Consider making your C function asynchronous - pass a completion handler which will be called to resume execution. If you can use ObjC - use ObjC block, it will bridge into Swift smoothly. If not - you can pass completion function and a context pointer, but then you will have to write some extra code to manually do the bridging. Note that this will require changing function implementation as well. Just calling the completion block in the end of blocking function won't change anything.

// from
result_t doStuff(arg_t arg);
// to
void doStuffAsync(arg_t arg, void (^completion)(result_t result));
// or
void doStuffAsync(arg_t arg, void (*completion)(void *ctx, result_t result), void *ctx);

If that is not possible, you can call C function on background thread:

// Completion handler
func doStuffAsync(arg_t arg, completion: @escaping (result_t) -> Void)
    DispatchQueue.global().async {
        let result = doStuff(arg)
        DispatchQueue.main.async {
            completion(result)
        }
   }
}

// async
func doStuffAsync(arg_t arg) async -> result_t
    withUnsafeContinuation { cont in
        DispatchQueue.global().async {
            let result = doStuff(arg)
            cont.resume(returning: result)
        }
    }
}
2 Likes

thanks for the hints.