我如何等待异步调度的块完成? [英] How do I wait for an asynchronously dispatched block to finish?
问题描述
我正在测试一些使用Grand Central Dispatch进行异步处理的代码.测试代码如下:
I am testing some code that does asynchronous processing using Grand Central Dispatch. The testing code looks like this:
[object runSomeLongOperationAndDo:^{
STAssert…
}];
测试必须等待操作完成.我当前的解决方案如下所示:
The tests have to wait for the operation to finish. My current solution looks like this:
__block BOOL finished = NO;
[object runSomeLongOperationAndDo:^{
STAssert…
finished = YES;
}];
while (!finished);
哪个看起来有些粗糙,您知道更好的方法吗?我可以公开队列,然后通过调用dispatch_sync
进行阻止:
Which looks a bit crude, do you know a better way? I could expose the queue and then block by calling dispatch_sync
:
[object runSomeLongOperationAndDo:^{
STAssert…
}];
dispatch_sync(object.queue, ^{});
...但是在object
上可能暴露得太多了.
…but that’s maybe exposing too much on the object
.
推荐答案
尝试使用dispatch_semaphore
.它应该看起来像这样:
Trying to use a dispatch_semaphore
. It should look something like this:
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:
认为该操作实际上不足以值得使用线程并改为同步运行,这也应正确执行.
This should behave correctly even if runSomeLongOperationAndDo:
decides that the operation isn't actually long enough to merit threading and runs synchronously instead.
这篇关于我如何等待异步调度的块完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!