6.6 Executing Non-UI Related Tasks Synchronously with GCD
来源:互联网 发布:在线源码编辑器 编辑:程序博客网 时间:2024/06/05 13:49
好久没来这学习了,也不想说什么了,因为 --怎么说都是错哦---
perform synchronous tasks that do not involve any UI-related code
用dispatch_sync 执行不操作UI的同步任务
比如后台下载文件
对于任何不操作UI的任务来讲,你可以使用全局的并发队列。它允许你同步的或异步的执行任务。同步执行是指队列内的任务同步执行,不会阻塞调用线程。(这里有个特殊情况:当使用dispatch_sync函数提交任务到并发或串行队列中。ios将尽可能在当前的线程上运行此任务,当前线程有可能是主线程,这主要要看当前的code path值,这是GCD优化编程导致的)
当你提交一个同步任务到一个并发队列,同时提交另一个同步任务到另一个并发队列。这两个同步任务将异步运行,因为他们在不同的并发队列里面。这一点要谨记,当你确定他们要同步时,你应该把它们提交到同一个并发队列。
来看个例子
首先是block
void (^printFrom1To1000)(void) = ^{
NSUInteger counter = 0;
for (counter = 1;
counter <= 1000;
counter++){
NSLog(@"Counter = %lu - Thread = %@",
(unsigned long)counter,
[NSThread currentThread]);
}
};
用GCD调用两次
dispatch_queue_t concurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_sync(concurrentQueue, printFrom1To1000);
dispatch_sync(concurrentQueue, printFrom1To1000);
运行代码会发现block对象是在主线程中运行的,这也验证了GCD优化的说法,disphtch_sync 函数尽可能用当前线程(派发任务的那个线程)来执行任务。
如果不用block对象,而用C函数,怎么做呢?
void printFrom1To1000(void *paramContext){
NSUInteger counter = 0;
for (counter = 1;
counter <= 1000;
counter++){
NSLog(@"Counter = %lu - Thread = %@",
(unsigned long)counter,
[NSThread currentThread]);
}
}
dispatch_queue_t concurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_sync_f(concurrentQueue,
NULL,
printFrom1To1000);
dispatch_sync_f(concurrentQueue,
NULL,
printFrom1To1000);
第一个参数指定优先级
DISPATCH_QUEUE_PRIORITY_LOW
DISPATCH_QUEUE_PRIORITY_DEFAULT
DISPATCH_QUEUE_PRIORITY_HIGH
优先级更高将咱用更多的cpu时间
第二个参数保留,记得传NULL哦
第三个就不说了,你懂的
- 6.6 Executing Non-UI Related Tasks Synchronously with GCD
- 6.7 Executing Non-UI Related Tasks Asynchronously with GCD
- 6.5 Performing UI-Related Tasks with GCD
- 6.12 Running Tasks Synchronously with Operations
- 6.10 Grouping Tasks Together with GCD
- 6.8 Performing Tasks After a Delay with GCD
- Non technical related question
- 什么是FCPA,Non-FCPA related, FCPA related
- With a Java ExecutorService, how do I complete actively executing tasks but halt the processing of w
- some non-tech related question
- Java Spring @Scheduled tasks executing twice
- androidStudio出现Executing tasks: app:assembleDebug
- Flex UI Related
- Queuing tasks with Redis
- UI Design Related Sites Collection
- Executing tasks: [:app:clean, :app:generateDebugSources, :app:mockableAndroidJar, :app:prepareDebug
- UI - GCD
- BSP introduction related with HW
- 网络游戏服务器架构设计
- 配置Jenkins的slave节点的详细步骤适合windows等其他平台
- C++ 设计抽象基类的策略
- 李小琳低调现身两会 手拿环保袋参加讨论
- Notification通知未显示
- 6.6 Executing Non-UI Related Tasks Synchronously with GCD
- Hive中小表与大表关联(join)的性能分析
- Apache 门户项目组介绍
- eclipse调优
- 编程之美:NIM(1)一排石头的游戏
- 浅析Android MediaProvider之二
- 在Android开发中调用Rest web服务
- Cocos2d-x HelloLua 介绍
- Android事件传递机制