Async

Async

https://github.com/duemunk/Async

 

Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch (GCD)

这是一个Swift中GCD的语法糖库。

 

Async sugar looks like this:

Async使用起来就像这样子:

Async.background {
    println("This is run on the background queue")
}.main {
    println("This is run on the main queue, after the previous block")
}

Instead of the familiar syntax for GCD:

替换了下面的这种显示方式:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
    println("This is run on the background queue")

    dispatch_async(dispatch_get_main_queue(), {
        println("This is run on the main queue, after the previous block")
    })
})

Install

pod 'Async', :git => 'https://github.com/duemunk/Async.git'

 

Benefits

  1. Less verbose code 更少的冗余代码
  2. Less code indentation 更少的缩进风

 

Things you can do

Supports the modern queue classes:

支持常用的queue类:

Async.main {}
Async.userInteractive {}
Async.userInitiated {}
Async.utility {}
Async.background {}

Chain as many blocks as you want:

你可以将不同的block链接起来使用:

Async.userInitiated {
    // 1
}.main {
    // 2
}.background {
    // 3
}.main {
    // 4
}

Store reference for later chaining:

也可以分开使用:

let backgroundBlock = Async.background {
    println("This is run on the background queue")
}

// Run other code here...

// Chain to reference
backgroundBlock.main {
    println("This is run on the \(qos_class_self().description) (expected \(qos_class_main().description)), after the previous block")
}

Custom queues:

自定义queue:

let customQueue = dispatch_queue_create("CustomQueueLabel", DISPATCH_QUEUE_CONCURRENT)
let otherCustomQueue = dispatch_queue_create("OtherCustomQueueLabel", DISPATCH_QUEUE_CONCURRENT)
Async.customQueue(customQueue) {
    println("Custom queue")
}.customQueue(otherCustomQueue) {
    println("Other custom queue")
}

Dispatch block after delay:

延时执行:

let seconds = 0.5
Async.main(after: seconds) {
    println("Is called after 0.5 seconds")
}.background(after: 0.4) {
    println("At least 0.4 seconds after previous block, and 0.9 after Async code is called")
}

Cancel blocks that aren't already dispatched:

取消没有启动的线程:

// Cancel blocks not yet dispatched
let block1 = Async.background {
    // Heavy work
    for i in 0...1000 {
        println("A \(i)")
    }
}
let block2 = block1.background {
    println("B – shouldn't be reached, since cancelled")
}
Async.main {
    // Cancel async to allow block1 to begin
    block1.cancel() // First block is _not_ cancelled
    block2.cancel() // Second block _is_ cancelled
}

Wait for block to finish – an ease way to continue on current queue after background task:

等待一个block运行结束:

let block = Async.background {
    // Do stuff
}

// Do other stuff

block.wait()

 

How does it work

The way it work is by using the new notification API for GCD introduced in OS X 10.10 and iOS 8. Each chaining block is called when the previous queue has finished.

本库使用了 iOS 8 提供的通知 API 来完成相关功能,每一个block都会在上一个block执行完了之后继续执行:

let previousBlock = {}
let chainingBlock = {}
let dispatchQueueForChainingBlock = ...

// Use the GCD API to extend the blocks
let _previousBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, previousBlock)
let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock)

// Use the GCD API to call back when finishing the "previous" block
dispatch_block_notify(_previousBlock, dispatchQueueForChainingBlock, _chainingBlock)

The syntax part of the chaining works by having class methods on the Async object e.g. Async.main {} which returns a struct. The struct has matching methods e.g. theStruct.main {}.

 

Known bugs

Modern GCD queues don't work as expected in the iOS Simulator. See issues 1322.

 

Known improvements

The dispatch_block_t can't be extended. Workaround used: Wrap dispatch_block_t in a struct that takes the block as a property.

 

Bonus stuff

There is also a wrapper for dispatch_apply() for quick parallelisation of a for loop.

Apply.background(100) { i in
    // Do stuff e.g. println(i)
}

Note that this function returns after the block has been run all 100 times i.e. it is not asynchronous. For asynchronous behaviour, wrap it in a an Async block like Async.main{ Apply.background(100) { ... } }.

 

 

 

时间: 2024-11-08 18:16:38

Async的相关文章

async 函数的含义和用法

本文是<深入掌握 ECMAScript 6 异步编程>系列文章的最后一篇. Generator函数的含义与用法 Thunk函数的含义与用法 co函数库的含义与用法 async函数的含义与用法 一.终极解决 异步操作是 JavaScript 编程的麻烦事,麻烦到一直有人提出各种各样的方案,试图解决这个问题. 从最早的回调函数,到 Promise 对象,再到 Generator 函数,每次都有所改进,但又让人觉得不彻底.它们都有额外的复杂性,都需要理解抽象的底层运行机制. 异步I/O不就是读取一个

JS文件加载:比较async和DOM Script

async与script动态加载都能使文件异步加载,本文叙述它们对页面渲染和load加载的影响方面. 目前我用demo.js作为执行文件操作.代码: var now = function() { return +(new Date()); } var t_s = now(); while(now() - t_s < 2000) {  } 用sleep.php作为请求文件操作.代码: <?php     sleep(3);     echo "var bb"; ?> 1

常用的script标签:defer和async

文章简介:我们常用的script标签,有两个和性能.js文件下载执行相关的属性:defer和async. 我们常用的script标签,有两个和性能.js文件下载执行相关的属性:defer和async defer的含义[摘自https://developer.mozilla.org/En/HTML/Element/Script] This Boolean attribute is set to indicate to a browser that the script is meant to be

Windows 8开发入门(五)弹出提示框MessageDialog与await、async关键字

在以前Silverlight.WPF中的弹出窗口提示中是MessageBox类中进行显示的,现在Windows 8中使用 Windows.UI.Popups命名空间下的MessageDialog类代替MessageBox. MessageDialog类有以下常用方法 和属性: ShowAsync():异步弹出消息框. Commands:添加命令,在弹出框界面上同步添加相应的按 钮. DefaultCommandIndex:设置默认按钮的索引,按ENTER键将激活该索引对应的命令按钮 Cancel

如何在现有代码中通过async/await实现并行

一项新技术或者一个新特性,只有你用它解决实际问题后,才能真正体会到它的魅力,真正理解它.也期待大家能够多分享解一些解决实际问题的内容. 在我们遭遇"黑色30秒"问题的过程中,切身体会到了异步的巨大作用(详见从ASP.NET线程角度对"黑色30秒"问题的全新分析),于是开始逐步地用async/await改造现有代码. 今天早上在将一个MVC Controller中的Action改为异步的时候突然发现--其中有7个方法调用可以并行执行. public async Tas

Windows Phone利用Async CTP实现异步加载数据

Async CTP是个好东西额,就是安装的时候比较坑- 跟N多补丁冲突,只要安装顺序对了才能顺利装上- 可以参考下以前写的:http://www.cnblogs.com/sun8134/archive/2011/09/19/2181030.html 异步是个好东西,可以让后台数据操作时前台也有反应而不是卡死 安装好Async CTP后,只要在wp项目中引用AsyncCtpLibrary_Phone.dll就可以使用async和await来实现异步加载了 MS已经封装好了一些异步操作,比如WebC

WF4.0 基础篇(二十四) Async Activity

项目说明: Async Activity Async的意思是异步,但有一点一定要注意,不能按字面理解,该Activity的功能是以同步的方式调用异步方法的Activity 建议看过[WF4.0 基础篇 (十三) InvokeMethod 调用方法 ]后,再看本文 类名 System.Activities.AsyncCodeActivity 文件 System.Activities.dll 结构说明 继承 Activity 是一个 abstract类 override 了 [CacheMetada

HTML5 script元素async、defer异步加载使用介绍

我对于HTML5感到兴奋不已的原因之一是它实现了众多业界期待已久的特性.我们一直需要输入框显示空白提示,但都是用JavaScript来实现的.我们也想要整个块都变成可被点击,也是使用JavaScript来实现. 现在WebKit为HTML5实现了SCRIPT标签的async异步属性.过去我们使用各种JavaScript技巧来做这种事情,但现在新的属性让防止阻塞变得相对容易. async - HTML属性 如我前面提到的,添加async属性非常简单:   复制代码 代码如下: <!-- 指定asy

java-spring添加@Async后报错.BeanCurrentlyInCreationException

问题描述 spring添加@Async后报错.BeanCurrentlyInCreationException 今天想优化一个action,所以在一个方法上添加了@Async的注解, 可是在启动程序时候却报了这个错,求指点. org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'cacheService': Bean with name 'cacheSe

NodeJS 实践:利用Node Async 解决 Callback Hell

在两年前的一个 MEAN 技术栈项目中曾经有过这样的一段的代码... Callback Hell 代码片段 UserLogin.findOne({email:email}) .populate({ path: 'toParty', select: 'fullname roleTypes' }) .exec(function(err, result){ if(err) return res.send(500,{msg:err}); if(result===null) return res.send