在返回的父线程返回之前,dispatch_async不会触发?

时间:2015-07-21 15:36:50

标签: objective-c grand-central-dispatch

我的问题是 - dispatch_async会立即触发吗?我发现创建线程必须在dispatch_async触发之前返回。

我的问题是我试图对第三方库进行异步调用似乎是同步的。我知道,我知道......我应该允许这些异步操作按预期运行,但我试图在复杂的多线程操作中这样做,我真的没有选择。

这是启动异步调用的原因

-(void)connect
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0) , ^{
        [device connect];
    });

    while(!connectCompleted)
    {
        NSLog(@"Sleeping..");
        [NSThread sleepForTimeInterval:1.0];
    }
}

这是在[device connect]成功连接后调用的委托函数:

- (void)didConnect:(BXPrinterController *)controller
printer:(BXPrinter *)printer
{
    connectCompleted = YES;

    NSLog(@"didConnect");
}

将dispatch_async缠绕在[device connect]上,委托永远不会被解雇;

2 个答案:

答案 0 :(得分:1)

  

dispatch_async会立即触发

当然不是!这就是async 的含义! “异步”(这是async所代表的)概念的整个基础是,这是在未来某个未指定时间运行的代码。与此同时,调用 dispatch_async的代码将一直持续到其结束而无需等待。

答案 1 :(得分:0)

如果由于某种原因你必须使一个呼叫看起来是同步的,我建议你先同步实现它(因为如果人们有足够的延迟你最终会这样做),然后你写一个帮助方法这是同步的:

Step 1: Create a dispatch_semaphore_t. 
Step 2: Start the asynchronous code, with every code path ending by sending a signal to the dispatch_semaphore_t. 
Step 3: Send a wait to the dispatch_semaphore_t. It wakes up, with no CPU time spent on it at all, just when the asynchronous code finishes.