【问题标题】:iOS serial tasks vs gcdiOS 串行任务与 gcd
【发布时间】:2014-02-22 12:11:48
【问题描述】:

对串行任务和 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
   }
}

非常感谢

【问题讨论】:

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


    【解决方案1】:

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

    __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;
    }
    

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

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 2022-08-23
      • 2017-03-01
      相关资源
      最近更新 更多