主队列上的dispatch_sync在单元测试中挂起 [英] dispatch_sync on main queue hangs in unit test

查看:89
本文介绍了主队列上的dispatch_sync在单元测试中挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用内置的Xcode单元测试框架SenTestingKit进行一些宏的中央调度代码的单元测试时遇到了麻烦.我设法解决了我为此做的问题.我有一个单元测试,该单元测试构建一个块并尝试在主线程上执行它.但是,该块实际上从未执行过,因此测试是挂起的,因为它是一个同步调度.

I was having some trouble unit testing some grand central dispatch code with the built in Xcode unit testing framework, SenTestingKit. I managed to boil my problem done to this. I have a unit test that builds a block and tries to execute it on the main thread. However, the block is never actually executed, so the test hangs because it's a synchronous dispatch.

- (void)testSample {

    dispatch_sync(dispatch_get_main_queue(), ^(void) {
        NSLog(@"on main thread!");
    });

    STFail(@"FAIL!");
}

导致测试挂起的测试环境是什么?

What is it about the testing environment that causes this to hang?

推荐答案

dispatch_sync在给定队列上运行一个块,并等待其完成.在这种情况下,该队列是主调度队列.主队列以FIFO(先进先出)的顺序在主线程上运行其所有操作.这意味着每当您调用dispatch_sync时,您的新块将被放置在该行的末尾,直到队列中的所有其他操作完成后,该块才开始运行.

dispatch_sync runs a block on a given queue and waits for it to complete. In this case, the queue is the main dispatch queue. The main queue runs all its operations on the main thread, in FIFO (first-in-first-out) order. That means that whenever you call dispatch_sync, your new block will be put at the end of the line, and won't run until everything else before it in the queue is done.

这里的问题是,您刚刚排队的块位于等待在主线程上运行的行的 end 处,而当前testSample方法在主线程上运行.队列末尾的块无法访问主线程,直到当前方法(自身)完成使用主线程的 为止.但是dispatch_sync表示提交一个块对象以在调度队列上执行,并等待该块完成.

The problem here is that the block you just enqueued is at the end of the line waiting to run on the main thread—while the testSample method is currently running on the main thread. The block at the end of the queue can't get access to the main thread until the current method (itself) finishes using the main thread. However dispatch_sync means Submits a block object for execution on a dispatch queue and waits until that block completes.

这篇关于主队列上的dispatch_sync在单元测试中挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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