dispatch_sync on main queue hangs in unit test

前端 未结 5 1102
太阳男子
太阳男子 2020-12-02 11:08

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 t

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 11:38

    The problem in your code is that no matter whether you use dispatch_sync or dispatch_async , STFail() will always be called, causing your test to fail.

    More importantly, as BJ Homer's explained, if you need to run something synchronously in the main queue, you must make sure you are not in the main queue or a dead-lock will happen. If you are in the main queue you can simply run the block as a regular function.

    Hope this helps:

    - (void)testSample {
    
        __block BOOL didRunBlock = NO;
        void (^yourBlock)(void) = ^(void) {
            NSLog(@"on main queue!");
            // Probably you want to do more checks here...
            didRunBlock = YES;
        };
    
        // 2012/12/05 Note: dispatch_get_current_queue() function has been
        // deprecated starting in iOS6 and OSX10.8. Docs clearly state they
        // should be used only for debugging/testing. Luckily this is our case :)
        dispatch_queue_t currentQueue = dispatch_get_current_queue();
        dispatch_queue_t mainQueue = dispatch_get_main_queue();
    
        if (currentQueue == mainQueue) {
            blockInTheMainThread();
        } else {
            dispatch_sync(mainQueue, yourBlock); 
        }
    
        STAssertEquals(YES, didRunBlock, @"FAIL!");
    }
    

提交回复
热议问题