简体   繁体   中英

How to stop dispatch_queue in ios?

I want to know the way for stopping asyncronous task when i click back button in navigation bar.I have done this code,but its not working ... 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];
                             }




                     });

in viewdisappear....

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

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

even though i suspend the thread it doesnt stop execution its keepon running in background.Anyone pls help me

Grand Central Dispatch is suitable for fire-and-forget tasks. If you want cancellable tasks, I would recommend using NSOperation and maybe NSOperationQueue .

No, you cannot do this. Use NSTimer instead.

dispatch_queue does not support cancel. However, you can use a block variable or some global variable to keep track of cancelable in the code of your dispatch_queue. The code in your dispatch_queue have to be able to stop working while cancel = YES (for example).

There are facilities such as dispatch_suspend() (along with dispatch_resume()). This will prevent any new blocks on a particular queue from being scheduled. It will not have any impact on already-running blocks . If you want to pause a block already scheduled and running, it is up to your code to check some conditions and pause. For suspending queues/cancelling operations, you should use NSOperation and NSOperationQueue instead of GCD.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM