如何在IOS中处理这种异步任务?

how to process this kind of async task in IOS?

我有三个任务。任务 1、任务 2 和任务 3。 task1 和 task2 是异步任务,即他们同时做任务,返回完成结果的时间是不可预测的。本来希望task1和task2同时做,有结果后再做task3。

dispatch_group_t dispatchGroup = dispatch_group_create();    

dispatch_group_async(dispatchGroup,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
   //do task1 async
});
dispatch_group_async(dispatchGroup,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
   //do task2 async
});
dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^(){

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    while (true) {
         sleep(0.2); //avoid cpu timeslice fully used
         //after get task1 and task2 result
         // do task3 
}});

我设计了上面的结构,但我总是得到不好的结果,比如如果task2是一个使用afnetworking的url post请求,我无法获得成功块。

任何人帮助我,我将不胜感激。

我认为有这样的解决方案:

__weak CLASS * weakSelf = self;
bool task1Done;
bool task2Done;

FIRST ONE TASK
task1Done = NO;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

       do something at background....

        dispatch_async(dispatch_get_main_queue(), ^{
            do some thing at main thread...
        [weakSelf task1Done];
        });
    });

SECOND TASK
task2Done = NO;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

       do something at background....

        dispatch_async(dispatch_get_main_queue(), ^{
            do some thing at main thread...
        [weakSelf task2Done];
        });
    });


============
-(void) task1Done
{   
    task1Done = YES;
    if (task1Done && task2Done) [self startTask3];
}

-(void) task2Done
{   
    task2Done = YES;
    if (task1Done && task2Done) [self startTask3];
}

-(void) startTask3
{
.....
}

ok,还有一个解决办法:

            dispatch_group_t group = dispatch_group_create();
            dispatch_queue_t queue1 = ...;
            dispatch_queue_t queue2 = ...;
            //add task to queue
            dispatch_group_async(group, queue1, ^{NSLog(@"Hello, World! TASK 1"); });
            dispatch_group_async(group, queue2, ^{NSLog(@"Hello, World! TASK 2"); });
//    wait forever
            dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
//    or wait with timeout
            dispatch_group_wait(group, DISPATCH_TIME_NOW);

            //Add notify for end of all tasks
            dispatch_group_notify(group, dispatch_get_main_queue(), ^{NSLog(@"Tasks 1 and 2 are done!");});

检查是否超时

dispatch_time_t waitTime = dispatch_time(DISPATCH_TIME_NOW, 10 * NSEC_PER_SEC);
long waitResult = dispatch_group_wait(group, waitTime);

if (waitResult == 0)
{
    // all done!
} else
{
    // time out
}

别忘了发布

dispatch_release(group);