Search code examples
iphoneiosmultithreadingasynchronousdispatch

How to suspend async task in iPhone?


I'm using async task for fetching images from Web on my main view controller. When user click on any cell on my table view I would like to suspend the Async tasks and go to another view.How Can I do this? Also I need to continue the tasks when user comes back to the Main view. My Code

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
            UIImage *imagefromWeb = [UIImage imageWithData:[NSData dataWithContentsOfURL:[IconArray objectAtIndex:indexPath.row]]];
            CGSize newSize= CGSizeMake(45.0,45.0);
            UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
            [imagefromWeb drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
            UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

            dispatch_async(dispatch_get_main_queue(), ^{
                cell.imageView.image=newImage;
                [cell setNeedsLayout];
                MAKE_IMAGE_CURVED(cell.imageView)
            });



        });

Solution

  • There are two reasonable approaches to this. One is to have a flag that is set when you want suspension to occur. The blocks on the background queue should check this flag before executing, and if set, wait for it to be unset. The flag is best constructed as a semaphore.

    However, GCD does support queue suspension. If you place your background requests on a custom queue (use dispatch_queue_create to make one), you can use dispatch_suspend on the queue to prevent further blocks from executing. Call dispatch_resume once you're ready to go again. This will not prevent the currently executing block(s) from completing - just future blocks. There's no sensible way I can think of to stop the execution of a block that's already mid-flow.

    For GCD documentation that covers both Semaphores and queue management, see here.