如何在前一个 dispatch_async 完成时执行第二个 dispatch_async?

How to execute second dispatch_async when previous first dispatch_async is finished?

我想按顺序添加一个 dispatch_async,但我不希望它们随机启动。 我想举个例子:

dispatch_async 1 开始...
dispatch_async1结束。

dispatch_async 2 开始...
dispatch_async2结束。

dispatch_async 3 开始...
dispatch_async3结束。

我需要更新一个sqlite,第一次调度中的信息对于第二次调度是必要的...

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%@",[connection currentRequest]);

    NSLog(@"connectionDidFinishLoading");
    NSError* error;
    NSString *responseKey = [self getResponseKey:connection];

    NSDictionary* response = [NSJSONSerialization JSONObjectWithData:[receivedData objectForKey:responseKey] options:kNilOptions error:&error];
    //NSLog(@"%@", response);

    if (error)
    {
        NSLog(@"Error: %@", error);
        NSLog(@"Error: Response strange format, not an NSArray and not a NSString!\n%@", [[NSString alloc] initWithData:[receivedData objectForKey:responseKey] encoding:NSUTF8StringEncoding]);
    }

    NSLog(@"connection url : %@", connection.currentRequest.URL);

    if ([[NSString stringWithFormat:@"%@", [connection currentRequest]] rangeOfString:@"getSynchroGuest?"].location != NSNotFound) 
    {
        NSLog(@"response success");
        if ([[response valueForKey:@"lignes"] isKindOfClass:[NSArray class]])
        {
            if ([[response valueForKey:@"lignes"] count] > 0)
            {
                dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
                    //Background Thread

                [self fillDataBaseWithDict:response];

                nbTotal = nbTotal + PACKET_FOR_SYNC;

                [self WebServiceSynchroGuest:self.activityIndicator withSynchroBtn:synchroBtn withNbTotal:nbTotal];
                                 });

            }
        }
...

提前致谢。

SOLUTION:
                dispatch_async(serialDispatchQueue, ^{
                    [self fillDataBaseWithDict:response];
                    nbTotal = nbTotal + PACKET_FOR_SYNC;

                    dispatch_async(dispatch_get_main_queue(), ^(void){
                    [self WebServiceSynchroGuest:self.activityIndicator withSynchroBtn:synchroBtn withNbTotal:nbTotal];
                    });
                });

Operation 代替 GCD 可以轻松实现您想要的。 Operation class 具有 addDependency(_ op: Operation) 功能。将您的代码放入 BlockOperation 个实例中,添加依赖项并将它们 运行 放入 OperationQueue

要按字面理解你的 Q,你必须嵌套调用:

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
^(void)
{ 
  // do some work
  …
  // finished here 

  // The next async code
  dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
  ^(void)
  { 
    // do some work
    …
    // finished here 

    // and so on

  }

}

但你真的应该考虑使用自定义串行队列或 NSOperation

连载Q:

dispatch_queue_t stepByStepQueue = dispatch_queue_create("com.you.taks", NULL);

dispatch_async(stepByStepQueue, 
^(void)
{
  // Step
}); 

dispatch_async(stepByStepQueue, 
^(void)
{
  // By
}); 

dispatch_async(stepByStepQueue, 
^(void)
{
  // Step
}); 

最好的方法是使用 NSOperations 并将它们添加到 queue.so 中,它将按完成顺序调用

但是如果你想以同样的方式做,那么定义完成块并在完成块中添加你的 dispatch_async2 & dispatch_Async3 并在最后调用这些完成块。

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            // do some long running processing here

            // Check that there was not a nil handler passed.
            if( completionHandler1 )
            {
               completionHandler1();
            }
            });
        });

定义你自己的串行队列

并添加这样的代码

 dispatch_queue_t yourSerialQueue = dispatch_queue_create("com.testcompany.testproduct.testserialqueue", DISPATCH_QUEUE_SERIAL);
 dispatch_async(yourSerialQueue, ^{ /* first task */ });
 dispatch_async(yourSerialQueue, ^{ /* second task to be executed after first task */ });

串行队列保证任务将按照提交顺序和串行方式执行(一次一个)

你可以把所有dispatch_async作为一个Serial Queue然后一个一个执行

dispatch_group_t组=dispatch_group_create();

dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {

    // block1
    NSLog(@"Block1");
    [ NSThread sleepForTimeInterval:5.0];
    NSLog(@"Block1 End");

});

dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
            // block2
    NSLog(@"block 2");
    [ NSThread sleepForTimeInterval:10.0];
    NSLog(@"Block2 End");

});
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {

    // block3
    NSLog(@"block 3");
    [ NSThread sleepForTimeInterval:15.0];
    NSLog(@"Block3 End");
});
dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {

    // block4
    NSLog(@"block 4");
    [ NSThread sleepForTimeInterval:20.0];
    NSLog(@"Block4 End");
});

像这样添加代码
您也可以设置优先级。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

});

});