1

我有一個由主文件和附加文件組成的內容。串行執行其他異步任務後執行異步任務

因此,這裏是問題:起初我需要下載,解包並插入數據庫附加文件,然後只對主文件做同樣的事情。其他文件需要下載串行,並且主文件必須在其後下載。

什麼是正確的做法?

現在我做這種方式:

- (void)checkIfPlacesAreDownloaded:(NSArray *)places{ 

    [SVProgressHUD showWithStatus:@"Downloading places"]; 

    dispatch_group_t group = dispatch_group_create(); 

    for(NSDictionary *place in places){ 

      BOOL result = [IDGDatabaseManager checkIfPlaceIsDownloaded:place]; 

      if(!result){ 
       dispatch_group_enter(group); 
       [self downloadPlace:place withCompletionHandler:^{ 
        [IDGDatabaseManager setPlaceDownloaded:[place objectForKey:@"place_ID"] 
             WithCompletionBlock:^(BOOL success, NSError *error) { 
              dispatch_group_leave(group); 
             }]; 
       }]; 

      } 
    } 

    dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 
     [self downloadExcursionWithParams:self.excursionDownloadResponse]; 
    }); 


} 

它只如果在「地方」排列一個文件的工作。如果有多個文件,它們開始被平行下載,並且不適合我。

+0

請更換dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH)主隊列或更改優先級 –

+0

@PKT好吧,我改成了dispatch_group_notify(組,dispatch_get_main_queue()。 ..你能告訴我有什麼區別嗎? – igrrik

+0

等等,所以...你不滿意_additional_文件是並行下載的嗎? – werediver

回答

1

我認爲downloadPlace:withCompletionHandler:方法在後臺併發隊列上異步工作。這就是文件下載並行運行的原因。我會使用一個專用的串行隊列替代或者乾脆做了下:

[SVProgressHUD showWithStatus:@"Downloading places"]; 

dispatch_group_t group = dispatch_group_create(); 

// create a serial background queue to run the file downloads 
dispatch_queue_attr_t qosAttribute = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0); 
dispatch_queue_t myQueue = dispatch_queue_create("com.YourApp.YourQueue", qosAttribute); 

for(NSDictionary *place in places){ 

    BOOL result = [IDGDatabaseManager checkIfPlaceIsDownloaded:place]; 

    if(!result){ 
     dispatch_group_enter(group); 

     // run the download async on the serial bg queue 
     __weak __typeof(self) weakSelf = self; 
     dispatch_async(myQueue, ^{ 
      __typeof(self) strongSelf = self; 

      // we need a semaphore to wait for the download completion 
      dispatch_semaphore_t sema = dispatch_semaphore_create(0); 
      [strongSelf downloadPlace:place withCompletionHandler:^{ 
       [IDGDatabaseManager setPlaceDownloaded:[place objectForKey:@"place_ID"] 
            WithCompletionBlock:^(BOOL success, NSError *error) { 
             dispatch_semaphore_signal(sema); 
            }]; 
      }]; 
      dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); 
      dispatch_group_leave(group); 
     }); 
    } 
} 

dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 
    [self downloadExcursionWithParams:self.excursionDownloadResponse]; 
}); 
+0

今天早上我寫了幾乎相同的解決方案,它的工作。想到,去午餐後,請回答我的問題,但你已經完成了) – igrrik