gpt4 book ai didi

ios - 如何在前一个 dispatch_async 完成时执行第二个 dispatch_async?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:22:07 27 4
gpt4 key购买 nike

我想按顺序添加一个 dispatch_async,但我不希望它们随机启动。我想举个例子:

dispatch_async 1 开始...
dispatch_async 1 结束。

dispatch_async 2 开始...
dispatch_async 2 结束。

dispatch_async 3 开始...
dispatch_async 3 结束。

我需要更新一个 sqlite,第一次调度中的信息对于第二次调度是必需的...

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"%@",[connection currentRequest]);

NSLog(@"connectionDidFinishLoading");
NSError* error;
NSString *responseKey = [self getResponseKey:connection];

NSDictionary* response = [NSJSONSerialization JSONObjectWithData:[receivedData objectForKey:responseKey] options:kNilOptions error:&error];
//NSLog(@"%@", response);

if (error)
{
NSLog(@"Error: %@", error);
NSLog(@"Error: Response strange format, not an NSArray and not a NSString!\n%@", [[NSString alloc] initWithData:[receivedData objectForKey:responseKey] encoding:NSUTF8StringEncoding]);
}

NSLog(@"connection url : %@", connection.currentRequest.URL);

if ([[NSString stringWithFormat:@"%@", [connection currentRequest]] rangeOfString:@"getSynchroGuest?"].location != NSNotFound)
{
NSLog(@"response success");
if ([[response valueForKey:@"lignes"] isKindOfClass:[NSArray class]])
{
if ([[response valueForKey:@"lignes"] count] > 0)
{
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread

[self fillDataBaseWithDict:response];

nbTotal = nbTotal + PACKET_FOR_SYNC;

[self WebServiceSynchroGuest:self.activityIndicator withSynchroBtn:synchroBtn withNbTotal:nbTotal];
});

}
}
...

提前致谢。

SOLUTION:
dispatch_async(serialDispatchQueue, ^{
[self fillDataBaseWithDict:response];
nbTotal = nbTotal + PACKET_FOR_SYNC;

dispatch_async(dispatch_get_main_queue(), ^(void){
[self WebServiceSynchroGuest:self.activityIndicator withSynchroBtn:synchroBtn withNbTotal:nbTotal];
});
});

最佳答案

定义你自己的串行队列

然后添加这样的代码

 dispatch_queue_t yourSerialQueue = dispatch_queue_create("com.testcompany.testproduct.testserialqueue", DISPATCH_QUEUE_SERIAL);
dispatch_async(yourSerialQueue, ^{ /* first task */ });
dispatch_async(yourSerialQueue, ^{ /* second task to be executed after first task */ });

串行队列保证任务将按照提交顺序和串行方式(一次一个)执行

关于ios - 如何在前一个 dispatch_async 完成时执行第二个 dispatch_async?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45076397/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com