Multiple DownloadTasks Consistently

I have n tasks sent to the server. When I run them using [taskN resume], they will run in parallel, but I want to run them sequentially - if the first task completes, another task starts. Any suggestions?

+4
source share
2 answers

For this, it is best to use NSOperationand NSOperationQueue.

It manages the task queue, and each of them runs in the background thread.

By setting the queue to have only one parallel operation, it will stand in the queue as you want.

You should...

  • NSOperation, . SYNCHRONOUS . , .

  • NSOperationQueue maximumNumberOfConcurrentOperations 1.

  • .

NSOperationQueue, , .

, , SO.

+4

:

:

    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:1];

    // first download task
    [queue addOperationWithBlock:^{
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); // create a semaphore


        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionTask *task1 = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {


            dispatch_semaphore_signal(semaphore); // go to another task
        }];
        [task1 resume];
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); // wait to finish downloading

    }];
    // second download task
    [queue addOperationWithBlock:^{
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);


        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionTask *task2 = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {


            dispatch_semaphore_signal(semaphore);
        }];
        [task2 resume];
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    }];

(task1, task2) , n-1.

, NSURLSession NSBlockOperation

+5

Source: https://habr.com/ru/post/1546806/


All Articles