如何在后台处理调度异步进程



Iam使用新的dispatch_queue接收Xmpp消息,同时更新我的选项卡计数Iam发送通知。但是更新我的Uitabar计数需要更多的时间。因此,我使用dispatch_queue_main()单独调用通知进程。但在更新我的选项卡计数时,它会让我的应用程序冻结几秒钟。。

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更新相关的代码?我见过有人报告说无法解释的速度减慢,然后说"哦,我不知道这也包括Core 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中的"时间档案器"工具运行该应用程序。有关如何使用该工具的演示,请参阅WWDC 2012关于构建并发用户界面的会议。

这些是我唯一的想法。

最新更新