轉自:https://blog.csdn.net/qq_34417314/article/details/80449484
for循環里的異步操作
開發中經常會遇到這樣一些情況,比如:
1.登錄失敗后的多次登錄重連場景。
2.在一個for循環遍歷里,有多種異步操作,需要在所有的異步操作完成后,也就是for循環的遍歷結束后,再去執行其他操作,但是不能卡主線程,這時候就需要用其他方法了。
我遇到的需求是,在一個for循環里有數據庫的查詢操作以及網絡請求操作,然后將數據庫的查詢和網絡請求的結果添加到一個臨時數組中,最后等for循環結束后,將臨時數組通過block回傳出去。
解決辦法如下:
- 串行隊列配合信號量
因為for循環不能卡主線程,所以我們首先要創建一個串行的隊列(並發的不可以),然后通過信號量來控制for循環,下面是模擬的一個操作:
1 printf("處理前創建信號量,開始循環異步請求操作\n"); 2 3 // 1.創建一個串行隊列,保證for循環依次執行 4 dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL); 5 6 // 2.異步執行任務 7 dispatch_async(serialQueue, ^{ 8 // 3.創建一個數目為1的信號量,用於“卡”for循環,等上次循環結束在執行下一次的for循環 9 dispatch_semaphore_t sema = dispatch_semaphore_create(0); 10 11 for (int i = 0; i<5; i++) { 12 // 開始執行for循環,讓信號量-1,這樣下次操作須等信號量>=0才會繼續,否則下次操作將永久停止 13 14 printf("信號量等待中\n"); 15 // 模擬一個異步任務 16 NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://github.com"]]; 17 NSURLSession *session = [NSURLSession sharedSession]; 18 NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 19 // 本次for循環的異步任務執行完畢,這時候要發一個信號,若不發,下次操作將永遠不會觸發 20 [tampArray addObject:@(i)]; 21 NSLog(@"本次耗時操作完成,信號量+1 %@\n",[NSThread currentThread]); 22 dispatch_semaphore_signal(sema); 23 24 }]; 25 [dataTask resume]; 26 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); 27 } 28 29 NSLog(@"其他操作"); 30 for (NSNumber *num in tampArray) { 31 NSLog(@"所有操作完成后的操作---> %@\n",num); 32 } 33 34 });
以上就是一個簡單的卡for循環的實例
- 實際場景中的應用
我遇到場景:
1.從相冊里取若干原圖,先獲取到縮略圖的數組,后根據縮略圖信息取原圖,這是一個可同步可異步的操作,鑒於卡頓考慮,采用異步取原圖的操作,
1 NSMutableArray *tmpPhotoes = [NSMutableArray array]; 2 // 這里用信號量卡 for 循環 來獲取原圖,等全部獲取完成再刷新UI 3 dispatch_queue_t serialQueue = dispatch_queue_create("getOriginalQueue", DISPATCH_QUEUE_SERIAL); 4 5 dispatch_async(serialQueue, ^{ 6 7 dispatch_semaphore_t sema = dispatch_semaphore_create(0); 8 9 [assets enumerateObjectsUsingBlock:^(PHAsset *tmpAsset, NSUInteger idx, BOOL * _Nonnull stop) { 10 11 /* 這里換成系統的方法也是一樣的,[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:option resultHandler:^(UIImage *result, NSDictionary *info) { 12 }];*/ 13 __block int time = 0; // 由於獲取原圖會有2次回調,PHImageResultIsDegradedKey為0時才為原圖 14 [[TZImageManager manager] getOriginalPhotoWithAsset:tmpAsset newCompletion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) { 15 // 原圖 16 if ([[info jk_stringForKey:PHImageResultIsDegradedKey] isEqualToString:@"0"]) { 17 [tmpPhotoes addObject:photo]; 18 } 19 time++; 20 if (time == 2) { 21 dispatch_semaphore_signal(sema); 22 } 23 }]; 24 25 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); 26 27 }]; 28 29 dispatch_async(dispatch_get_main_queue(), ^{ 30 if (tmpPhotoes.count) { 31 [self refreshImageDataWithPhotos:tmpPhotoes assets:assets]; 32 } 33 }); 34 });
2.外界多個渠道隨時可能來查詢一個會話列表數組的數據,但是原始的數組里沒有包含想要的東西,需要包裝一下再供外界使用。首先需要創建一個條件鎖,防止這個列表數據被多方訪問造成資源搶奪,其次循環遍歷原始數組,通過數據庫查詢和網絡請求操作重新包裝會話列表里的數據,最后等待for循環結束,將包裝過的數組回傳給外界以供使用。
1 /** 會話列表 */ 2 -(void)getConversationList:(void(^)(NSArray *conversationList))handler { 3 // 條件鎖,若當前資源可獲取則進行下一步,否則等待條件鎖完成才能訪問 4 if ([self.lock obtain]) { 5 BBLog(@"BigBang- 獲取資源中"); 6 // 會話列表 7 NSArray *oriList = [[BBConversationManager manager] getConversationList]; 8 9 dispatch_queue_t serailQueue = dispatch_queue_create("conversationQueue", DISPATCH_QUEUE_SERIAL); 10 dispatch_async(serailQueue, ^{ 11 12 // 每次重置,防止 dispose 13 self.sema = nil; 14 self.sema = dispatch_semaphore_create(1); 15 BBLog(@"BigBang- CrashInfo -- 信號量創建 當前線程---%@",[NSThread currentThread]); 16 // 臨時數組 存儲變換后的會話模型 17 __block NSMutableArray *temList = [NSMutableArray array]; 18 if (oriList.count > 0) { 19 [oriList enumerateObjectsUsingBlock:^(RCConversation *conversation, NSUInteger idx, BOOL * _Nonnull stop) { 20 21 NSString *identifier = conversation.targetId; 22 RCMessage *message = [[RCIMClient sharedRCIMClient] getMessage:conversation.lastestMessageId]; 23 24 if ([conversation conversationType] == ConversationType_PRIVATE || [conversation conversationType] == ConversationType_SYSTEM) { 25 26 BBLog(@"BigBang- CrashInfo 信號量-1"); 27 dispatch_semaphore_wait(self.sema, DISPATCH_TIME_FOREVER); 28 29 // 本地存在,直接從本地數據庫取 這里是一個數據庫的查詢操作,是在子線程中進行的 30 if ([BBUserTable isUserExist:identifier]) { 31 32 BBConversationListModel *model = [[BBConversationListModel alloc] initWithRCMessage:message userInfo:[BBUserTable gerUserWithID:identifier]]; 33 model.unreadMessageCount = conversation.unreadMessageCount; 34 if ([conversation conversationType] == ConversationType_SYSTEM) { 35 [[BBConversationManager manager] setConversationToTop:ConversationType_SYSTEM targetId:identifier isTop:YES]; 36 } 37 38 [temList addObject:model]; 39 // 從數據庫獲取完成 發送信號 繼續下一次取值 40 dispatch_semaphore_signal(self.sema); 41 BBLog(@"BigBang- CrashInfo 數據庫 信號量+1"); 42 43 }else { 44 45 // 本地不存在 調接口請求數據 這里是一個網絡請求操作,無論請求成功與否,都要將信號量恢復 46 [[BBDataManager manager] asyncGetUserInfoWithUserID:identifier result:^(NSDictionary *userInfo) { 47 48 BBUserInfo *newUserInfo = [[BBUserInfo alloc] initWithUserID:identifier userName:[NSString stringWithFormat:@"%@",userInfo[@"nickname"]] avatar:[NSString stringWithFormat:@"%@",userInfo[@"avatar"]] level:[NSString stringWithFormat:@"%@",userInfo[@"level"]]]; 49 BBConversationListModel *model = [[BBConversationListModel alloc] initWithRCMessage:message userInfo:newUserInfo]; 50 model.unreadMessageCount = conversation.unreadMessageCount; 51 52 if ([conversation conversationType] == ConversationType_SYSTEM) { 53 [[BBConversationManager manager] setConversationToTop:ConversationType_SYSTEM targetId:identifier isTop:YES]; 54 } 55 56 [temList addObject:model]; 57 58 BBLog(@"BigBang- CrashInfo 網絡請求 信號量+1"); 59 dispatch_semaphore_signal(self.sema); 60 [BBUserTable saveUserInfoWithModel:newUserInfo]; 61 62 } error:^(NSError *error){ 63 64 BBLog(@"BigBang- CrashInfo 網絡請求失敗 信號量+1"); 65 dispatch_semaphore_signal(self.sema); 66 67 }]; 68 } 69 } 70 }]; 71 // 結束操作后,將鎖打開,以供后面的訪問 72 if (handler) { 73 if (temList.count) { 74 dispatch_async(dispatch_get_main_queue(), ^{ 75 handler(temList); 76 }); 77 BBLog(@"BigBang- CrashInfo 獲取數據完畢,回傳顯示 當前線程--%@ ",[NSThread currentThread]); 78 } 79 } 80 [self.lock finish]; 81 }else { 82 if (handler) { 83 handler(nil); 84 } 85 [self.lock finish]; 86 } 87 }); 88 89 }else { 90 BBLog(@"BigBang- 搶奪資源中,等待當前獲取資源結束繼續進行"); 91 }
}
上面的條件鎖的文件如下: .h 文件 這里的 < > 不能用,請自行替換 ‘ 為 < >
使用方法為:
self.lock = [[BBResourceLock alloc] init];
if ([self.lock obtain]) {
// 各種任務
…
// 結束后將鎖關閉
[self.lock finish];
}
具體的文件如下:
import ‘Foundation/Foundation.h’
@interface BBResourceLock : NSObject
/**
- 獲取資源,如果資源已經被獲取過則返回 NO,否則返回 YES
- @return 如果資源已經被獲取過則返回 NO,否則返回 YES
*/
-(BOOL)obtain;
/**
等待資源可用
如果資源沒有被獲取過 則獲取資源並返回YES
如果資源被其他線程獲取則等待,直到資源可用並返回 YES
如果資源是被同一線程獲取則不會等待,並且返回NO
@return YES/NO
*/
-(BOOL)wait;
/**
釋放占用的資源
*/
-(void)finish;
@end
.m文件
#import “BBResourceLock.h”
@interface BBResourceLock ()
/** 當前線程 /
@property (nonatomic,strong) NSThread mOccupiedThread;
/ 條件 */
@property (nonatomic,strong) NSCondition *mCondition;
@end
@implementation BBResourceLock
- (instancetype)init
{
self = [super init];
if (self) {
self.mCondition = [[NSCondition alloc] init];
}
return self;
}
/**
-
獲取資源,如果資源已經被獲取過則返回 NO,否則返回 YES
-
@return 如果資源已經被獲取過則返回 NO,否則返回 YES
*/
-(BOOL)obtain {@synchronized(self.mCondition) {
if (self.mOccupiedThread) {
return NO;
}else {
self.mOccupiedThread = [NSThread currentThread];
return YES;
}
}
}
/**
等待資源可用
如果資源沒有被獲取過 則獲取資源並返回YES
如果資源被其他線程獲取則等待,直到資源可用並返回 YES
如果資源是被同一線程獲取則不會等待,並且返回NO
@return YES/NO
*/
-(BOOL)wait {
@synchronized (self.mCondition) {
if (!self.mOccupiedThread) {
return [self obtain];
}
if (self.mOccupiedThread == [NSThread currentThread]) {
return YES;
}
[self.mCondition wait];
return [self obtain];
}
}
/**
釋放占用的資源
*/
-(void)finish {
@synchronized(self.mCondition) {
self.mOccupiedThread = nil;
[self.mCondition signal];
}
}
@end
以上就是關於for循環的異步任務處理
