如何等待异步调度块完成? [英] How do I wait for an asynchronously dispatched block to finish?

查看:34
本文介绍了如何等待异步调度块完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试一些使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆