在开发过程中,碰到过在一个页面 用到了多个网络请求,而且根据业务需求,需要有次序的执行A B C 网络请求?
你可能会想到,我在A的请求成功回调里去处理B,在B的回调里去请求C,但你后来会发现整个页面的网络请求逻辑已经乱套了.因为往往在网络请求之后会去做一些UI界面的操作.
那应该如何高质量的处理这种情况呢?请往下看:
1.通过信号量来实现(信号量就三个函数dispatch_semaphore_create , dispatch_semaphore_wait , dispatch_semaphore_signal)
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//任务1
dispatch_async(quene, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
for (int i = 0; i<10; i++)
{
NSLog(@"j的值是:%d",i);
}
dispatch_semaphore_signal(semaphore);
});
//任务2
dispatch_async(quene, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
for (int i = 0; i<20; i++)
{
NSLog(@"i的值是:%d",i);
}
dispatch_semaphore_signal(semaphore);
});
(推荐)通过 NSOperationQueue 中的依赖关系来操作,NSOperation 是对GCD的封装实现的,所以其优点肯定是高于GCD的。
NSOperationQueue * queueeTest = [[NSOperationQueue alloc]init];
queueeTest.maxConcurrentOperationCount = 1;
NSBlockOperation * optionA = [NSBlockOperation blockOperationWithBlock:^{
for (int i = 0; i<10; i++)
{
NSLog(@"i的值是:%d",i);
}
}];
NSBlockOperation * optionB = [NSBlockOperation blockOperationWithBlock:^{
for (int j = 0; j<20; j++)
{
NSLog(@"j的值是:%d",j);
}
}];
//A依赖于B
[optionA addDependency:optionB];
[queueeTest addOperation:optionA];
[queueeTest addOperation:optionB];
网友评论