2017-07-14 37 views
0

在我的应用程序中,我使用以下方法来检查某些变量的值,这些变量只能在主线程上访问。iOS ObjC:为什么mainThread上的dispatch_sync不工作而app在后台接收APNs提取?

- (void) xttSyncOnMainThread:(void (^)(void))prmBlock { 
    if (![NSThread isMainThread]) { 
     dispatch_queue_t mtQueue = dispatch_get_main_queue(); // will be executed 
     // execution is stuck here 
     dispatch_sync(mtQueue, prmBlock); // won't be executed 
    } else { 
     prmBlock(); 
    } 
} 

我需要移动:

现在,我开始实施的APN,当我的应用程序是通过APN的唤醒似乎代码执行(背景)总是停留在点使用注释显示所有的代码到非MT队列还是我错过了别的?

非常感谢!

回答

0

好了,经过一番更多的测试,我发现,在我的情况下(而在问题的代码工作得很好)的问题,从意外调用从completionhandler来APN代表过早。

0

因为主队列上的dispatch_sync导致死锁。关于dispatch_sync和主队列

更多信息,例如这里:

dispatch_sync on main queue hangs in unit test

Why dispatch_sync() call on main queue is blocking the main queue?

你能只使用dispatch_async方法?

+0

您认为这会导致死锁吗?如果我不在后台,而是我的应用程序处于“主动模式”,它可以很好地工作。我甚至检查当前线程是否是避免死锁的主线程。 – McMini

+0

我的意见并不重要你在主队列上运行dispatch_sync。因为在启动块之前主队列已经完成了。但是这不会发生,因为你的队伍正在排队并等待被派遣。你阻止自己。也许我的描述不是最好的,但这基本上是写在相关问题上的。 –

+0

我不确定你需要多少同步电话。但我会尽量简化你的方法,只能通过异步调用在主线程上运行。 dispatch_get_main_queue(),^ {prmBlock()} –

-1
- (void) xttSyncOnMainThread:(void (^)(void))prmBlock { 

    dispatch_async(dispatch_get_main_queue(), ^{ 
    //code here to perform 
    }); 
} 
0

为什么你传递prmBlock到dispatch_sync

平时很喜欢

dispatch_sync(dispatch_get_main_queue(), ^(void) { 
     // write the code that is to be executed on main thread 
}); 

但是如果你使用disptch_sync它会等待块完成执行,然后返回。如果你不希望阻止执行使用

dispatch_async(dispatch_get_main_queue(), ^(void) { 
     // write the code that is to be executed on main thread 
}); 
+0

我使用带参数的方法来避免重复检查代码是否已经在主线程中 – McMini

+0

我不明白你的问题你想做什么在主线程中,请清除你的问题,无论你想在主线程上做什么,都要在^(void){ //写出要在主线程上执行的代码 }如果你只是将prmBlock传递给队列在哪里执行,或者你甚至想在prmBlock中做什么? – hariszaman

相关问题