小编典典

如何等待异步调度的块完成?

all

我正在测试一些使用 Grand Central Dispatch 进行异步处理的代码。测试代码如下所示:

[object runSomeLongOperationAndDo:^{
    STAssert...
}];

测试必须等待操作完成。我目前的解决方案如下所示:

__block BOOL finished = NO;
[object runSomeLongOperationAndDo:^{
    STAssert鈥�
    finished = YES;
}];
while (!finished);

哪个看起来有点粗糙,你知道更好的方法吗?我可以公开队列,然后通过调用阻止dispatch_sync

[object runSomeLongOperationAndDo:^{
    STAssert...
}];
dispatch_sync(object.queue, ^{});

“那个”可能在上面暴露太多了object


阅读 74

收藏
2022-08-01

共1个答案

小编典典

尝试使用dispatch_semaphore. 它应该看起来像这样:

dispatch_semaphore_t sema = dispatch_semaphore_create(0);

[object runSomeLongOperationAndDo:^{
    STAssert...

    dispatch_semaphore_signal(sema);
}];

if (![NSThread isMainThread]) {
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
} else {
    while (dispatch_semaphore_wait(sema, DISPATCH_TIME_NOW)) { 
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0]]; 
    }
}

即使runSomeLongOperationAndDo:确定操作实际上没有足够长以值得线程化并改为同步运行,这也应该正确运行。

2022-08-01