如何在后台处理调度asynchronous进程?

Iam使用新的dispatch_queue接收Xmpp消息,同时更新我的​​tabbar计数IAM发送通知。 但是需要更多时间来更新我的Uitabbar计数。 所以我用dispatch_queue_main()单独调用通知进程。 但它使我的应用程序冻结了几秒钟,而更新我的tabbar计数..

dispatch_queue_t exampleQueue = dispatch_queue_create( "xmpp_message", NULL ); dispatch_async(exampleQueue, ^{ // code for proceesing messages.... dispatch_queue_t queue=dispatch_get_main_queue(); dispatch_async(queue, ^{ [self sendNotification:msg]; }); }); 

任何人都可以帮忙,在不冻结的情况下处理通知过程。

上面的语法看起来不错,并采用适当的技术将任务分派给后台进程,但是随后将UI更新重新分派回主队列。 所以,你可能不得不扩大你的调查。 考虑到这一点,您可能需要考虑:

  • 您是否确定在“处理消息的代码”部分下没有UI更新相关代码? 我看到有人报告说不明原因的缓慢起伏,然后说“哦,我也不知道这包括核心graphics”。 我知道这不太可能,但仔细检查。

  • 这是一个愚蠢的问题,但是你把NSLog语句放在这里,在两个块的开始? 通过这样做,你可以确定哪个队列是罪魁祸首(如果有的话),更好地了解队列的进入和退出等。不知道你的代码,我担心“处理消息的代码”花费的时间太长。

    所以你可能会:

     dispatch_queue_t exampleQueue = dispatch_queue_create( "xmpp_message", NULL ); dispatch_async(exampleQueue, ^{ NSLog(@"%s dispatched to xmpp_message", __FUNCTION__); // code for processing messages.... dispatch_queue_t queue = dispatch_get_main_queue(); dispatch_async(queue, ^{ NSLog(@"%s re-dispatched to main queue", __FUNCTION__); [self sendNotification:msg]; NSLog(@"%s finished dispatch to main queue", __FUNCTION__); }); NSLog(@"%s finished dispatched to xmpp_message", __FUNCTION__); }); // if not ARC or supporting iOS versions prior to 6.0, you should release the queue dispatch_release(exampleQueue); 
  • 你也可能也想确保你没有自定义队列的串行性质造成的问题。 是否需要串行性质,还是可以考虑并发队列?

    所以试试:

     dispatch_queue_t exampleQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // or in recent versions of iOS, you can use dispatch_queue_create( "xmpp_message", DISPATCH_QUEUE_CONCURRENT ); dispatch_async(exampleQueue, ^{ NSLog(@"%s dispatched to xmpp_message", __FUNCTION__); // code for processing messages.... dispatch_queue_t queue = dispatch_get_main_queue(); dispatch_async(queue, ^{ NSLog(@"%s re-dispatched to main queue", __FUNCTION__); [self sendNotification:msg]; }); }); 
  • 最后,您可能想要使用Instruments中的“时间分析器”工具来运行应用程序。 查看关于构build并行用户界面的WWDC 2012会话,以演示如何使用该工具。

这是跳出我的唯一想法。