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

时间:2015-08-28 12:45:13

标签: ios asynchronous concurrency grand-central-dispatch

我有三个任务。 task1,task2和task3。 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请求,我就无法获得成功阻止。

有人帮助我,我会很感激。

2 个答案:

答案 0 :(得分:0)

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

__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
{
.....
}

答案 1 :(得分:0)

好的,还有一个解决方案:

            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);