开发者

Blocks get fired one after another when using dispatch_group_async

URLs in the array are called one after another. Should it not be called all at once, like nsoperationqueue? Please help me here, Thanks

  - (void) allTasksDone {
    NSLog(@"DONE");
  }

  - (void) callM开发者_C百科ultiple {
    dispatch_queue_t myQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
    dispatch_group_t group = dispatch_group_create();
    NSArray *urls = [NSArray arrayWithObjects:
                     @"http://www.a.com",
                     @"http://www.b.com",
                                     @"http://www.c.com",

                     nil];

    for (NSString *url in urls) {


        dispatch_group_async(group, myQueue, ^{


            NSLog(url);

            NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
            NSHTTPURLResponse *response = NULL;
            NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];


            NSLog(@"COMPLETE");

        });
    }

    dispatch_group_notify(group, myQueue, ^{
        [self allTasksDone];
    });

  }


  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {        

     [self callMultiple];

     [self.window makeKeyAndVisible];

     return YES;
  }


dispatch_queue_create creates FIFO queue. It takes blocks one-by-one from queue in the same order theme were added. If you would like to perform blocks concurrently you can create different queues for each block or get use of one of global queues.

dispatch_queue_t dispatch_get_global_queue(
   long priority,
   unsigned long flags);

There are 3 global queues, distinguished by priority.

enum {
   DISPATCH_QUEUE_PRIORITY_HIGH = 2,
   DISPATCH_QUEUE_PRIORITY_DEFAULT = 0,
   DISPATCH_QUEUE_PRIORITY_LOW = -2,
};

Those queues does not wait for previous block completion. So your downloads will be performed concurrently.


First, no, async() does not guarantee asynchronous execution of the blocks. That'll only happen if any given block is blocked waiting for something to happen. GCD will then spin up another thread.

However, if the system is already relatively loaded, GCD isn't going to spin up a new thread to do some work if work is already taking place.

Secondly, there is no reason to push NSURLRequests into the background via GCD. NSURLRequest supports asynchronous downloads already.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜