Asynchronous url requests inside dispatch_async

前端 未结 3 1540
悲&欢浪女
悲&欢浪女 2020-12-28 10:35

I am trying to implement asynchronous url requests in a particular function, I want all these requests to complete and then do a particular action but the action precedes th

3条回答
  •  囚心锁ツ
    2020-12-28 11:32

    @tkanzakic is on the right path. The correct construct to use is the dispatch_group_t. But the implementation could be improved. By using a semaphore you can launch all your downloads asynchronously and still make sure that you don't have too many running concurrently. Here is a code sample that illustrates how you should use dispatch_group_t as well as make all your downloads parallel:

    dispatch_queue_t fetchQ = dispatch_queue_create("Featured Doc Downloader", NULL);
    dispatch_group_t fetchGroup = dispatch_group_create();
    
    // This will allow up to 8 parallel downloads.
    dispatch_semaphore_t downloadSema = dispatch_semaphore_create(8);
    
    // We start ALL our downloads in parallel throttled by the above semaphore.
    for (int i=0; i

提交回复
热议问题