【问题标题】:How to stop dispatch_queue in ios?如何在 ios 中停止调度队列?
【发布时间】:2014-09-11 12:28:53
【问题描述】:

我想知道当我点击导航栏中的后退按钮时停止异步任务的方法。我已经完成了这段代码,但它不起作用...... dispatch_group_t imageQueue = dispatch_group_create();

dispatch_group_async(imageQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
                     ^{
                         imagedata=[[NSMutableArray alloc]init];

                         for (int i=0; i<[imageURL count]; i++)
                         {
                             NSLog(@"clicked ");

                           [imagedata addObject:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[imageURL objectAtIndex:i]]]]];

 [[NSNotificationCenter defaultCenter] postNotificationName:@"Avatardownloaded" object:imagedata   userInfo:nil];
                             }




                     });

在视图中消失....

-(void)viewDidDisappear:(BOOL)animated
{
    dispatch_suspend(imageQueue);

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Avatardownloaded" object:nil];
    [[NSNotificationCenter defaultCenter]release];
    [avatarimages release];
    [imagedata release];
    [imageURL release];   
}

即使我暂停线程,它也不会停止执行,它会在后台继续运行。任何人请帮助我

【问题讨论】:

标签: ios grand-central-dispatch dispatch


【解决方案1】:

Grand Central Dispatch 适用于即发即弃的任务。如果您想要可取消的任务,我建议您使用NSOperation 或者NSOperationQueue

【讨论】:

  • 还有一个疑问..我正在使用 SBJson Parser,bcz 我无法解析换行符,回车符..为了解析我删除了这些字符,但是在 UI 中如何显示带有换行符的语句我使用 SBJson 解析..
【解决方案2】:

不,你不能这样做。请改用 NSTimer。

【讨论】:

    【解决方案3】:

    dispatch_queue 不支持取消。但是,您可以使用块变量或一些全局变量来跟踪 dispatch_queue 代码中的可取消。您的 dispatch_queue 中的代码必须能够在 cancel = YES 时停止工作(例如)。

    【讨论】:

      【解决方案4】:

      有诸如dispatch_suspend()(以及dispatch_resume())之类的工具。这将防止在特定队列上安排任何新块。它不会对已经运行的块产生任何影响。如果您想暂停已安排并正在运行的块,则由您的代码检查某些条件并暂停。对于暂停队列/取消操作,您应该使用 NSOperation 和 NSOperationQueue 而不是 GCD。

      【讨论】:

      • 记住:NSOperations 只是一个建立在 Grand Central Dispatch 之上的 API。因此,当您使用 NSOperations 时,您仍在使用 Grand Central Dispatch。只是 NSOperations 为您提供了一些您可能会使用的附加功能。您可以使某些操作依赖于其他操作,在汇总项目后重新排序队列,重用操作,取消或暂停它们,添加各种操作之间的依赖关系。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      相关资源
      最近更新 更多