如何强制GCD在主队列上执行当前块? [英] How to force GCD perform current blocks on main queue?

查看:73
本文介绍了如何强制GCD在主队列上执行当前块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有工作线程任务,该任务使用以下命令在队列中发布结果:

I have worker thread task that published results on main queue using:

// on worker queue

// (long-running task)

// publish results on main queue
dispatch_async(dispatch_get_main_queue(), ^(void) {
    _finished = YES;
});

我如何坐在主队列(主CXTest线程)中,并强制gcd处理队列上的当前任务,如:

How can i sit in main queue (main CXTest thread) and force gcd handle current tasks on the queue like:

// on main queue
while (!_finished) {
    [NSThread sleepForTimeInterval:0.1];
    // TODO : force main queue to perform current blocks
}

显而易见的解决方案是在工作线程中设置_finished,但是由于某些原因我不能这样做(只能在主线程中触摸UI控件)

The obvious solution is to set _finished in worker thread, but i can't do that for some reason (UI controls can be touched in main thread only)

推荐答案

您可以像这样泵送运行循环:

You can pump your run loop like this:

while (!_finished) {
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1];
}

最终将耗尽主队列,将 _finished 设置为 YES .

it will drain main queue eventually, setting _finished to YES.

但是我建议您使用异步测试助手,例如 XCAsyncTextCase ,也可以使用期望具有非常方便的异步帮助器.其他测试框架也可能具有此类扩展.

But I'd recommend you to use an async test helper like XCAsyncTextCase, also expecta has quite handy async helper. Other test frameworks may have such extensions as well.

这篇关于如何强制GCD在主队列上执行当前块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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