ios嵌套的非同步並行任務情境

來源:互聯網
上載者:User

標籤:dispatch_group   嵌套   非同步   並行任務   

情境1:

從資料來源讀到N個值,然後需要遍曆這N個值,分別發起http請求。處理完成之後,調用一個最終匯總的方法

這個情境如果用js的async架構,很容易就能實現:

async.series([task1, task2, task3], function(err){    // 匯總代碼});function task1(callback){    // http請求    callback(null);}function task2(callback){    // http請求    callback(null);}function task3(callback){    // http請求    callback(null);}

但是在ios裡,就比較麻煩,最後是用dispatch_group實現的:

dispatch_group_t group = dispatch_group_create();            while([rs next]){                    dispatch_group_enter(group);                   [syncService refreshMembersWithEnterpriseId:enterpriseId LatestSyncTime:latestSyncDate Block:^(BOOL flag){        dispatch_group_leave(group);    }];}        dispatch_group_notify(group, dispatch_get_main_queue(), ^{    // 匯總代碼});

情境2:

後來需求變化了,情境更複雜了點。針對每個值,都要發起多個http請求(情境1隻需要請求1次)。所有請求都結束以後,再調用匯總方法

所以一開始我寫成類似這樣:

dispatch_group_t group = dispatch_group_create();            while([rs next]){                    dispatch_group_enter(group);        dispatch_group_t group_inner = dispatch_group_create();                    dispatch_group_enter(group_inner);    [syncService refreshMembersWithEnterpriseId:enterpriseId LatestSyncTime:latestSyncDate Block:^(BOOL flag){        dispatch_group_leave(group_inner);    }];                    dispatch_group_enter(group_inner);    [syncService refreshReportsWithEnterpriseId:enterpriseId LatestSyncTime:latestSyncDate Block:^(BOOL flag){        dispatch_group_leave(group_inner);    }];                    dispatch_group_notify(group_inner, dispatch_get_global_queue(0, 0), ^{        dispatch_group_leave(group);    });}            dispatch_group_notify(group, dispatch_get_main_queue(), ^{    // 匯總代碼});

寫完之後發現,其實在這個情境下,不需要嵌套group,共用一個group也沒問題

dispatch_group_t group = dispatch_group_create();            while([rs next]){                                    dispatch_group_enter(group);    [syncService refreshMembersWithEnterpriseId:enterpriseId LatestSyncTime:contactLatestSync Block:^(BOOL flag){        dispatch_group_leave(group);    }];                    dispatch_group_enter(group);    [syncService refreshReportsWithEnterpriseId:enterpriseId LatestSyncTime:reportLatestSync Block:^(BOOL flag){        dispatch_group_leave(group);    }];}dispatch_group_notify(group, dispatch_get_main_queue(), ^{    // 匯總代碼});

因為這裡並不需要針對每個組做匯總處理,如果每個組還有自己的匯總邏輯需要執行的話,就需要嵌套group了

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.