iOS串行任务vs gcd

时间:2014-02-22 03:56:13

标签: ios objective-c grand-central-dispatch

有关于串行任务和dispatch_queue的问题 我的样本是: 有1101个项目插入到sqlite中,我使用'insert into select union all select'来做插入作业,但是sqlite只支持500个项目,所以单独的数据并逐个插入, 问题是我的数据库操作模型在一个dispatch_queue(一个串行队列)中处理所有sql,并在完成一个任务时使用一个块来做回调。

所以如果我想在task1成功完成后做task2,我就不能,因为调度队列 关于这个设计的任何想法或建议,或者如果保留调度队列,我该怎么办?

当前代码:

for(int i = 0; i<n;i++)  //n tasks
{
   do a task in dispatch queue:^(BOOL success){
      if(success)
       do task 2
   }
}
非常感谢

1 个答案:

答案 0 :(得分:0)

考虑到队列是串行的,这样的事情怎么样:

__block NSError* _task_error = nil;

for(int i = 0; i<n;i++)  //n tasks
{
   dispatch_async(queue, ^ {
      if(_task_error != nil) return; //There was an error in a previous task - we done.

      //Try performing operation, and on error - set _task_error to hold information on the problem.
   }
}

//Finally, add cleanup operation to log final result.
dispatch_async(queue, ^ {
   //Write to your log here, notify handlers on error, etc.

   //Finally, clean the _task_error so next batch has a clean start.
   _task_error = nil;
}

由于队列是串行的并且FIFO是有保证的,因此块将按顺序执行,如果先前的任务不成功,则不会尝试任务。

相关问题