这是一个简单的对NSThread的包装,用于在完全相同的线程上运行代码块。它保证是最先入先出(FIFO)的。
此代码基于以下StackOverflow答案:[http://stackoverflow.com/a/22091859](http://stackoverflow.com/a/22091859)。已经获得原始作者的同意重新分发(Marc Haisenko)。
let thread = Thread()
thread.enqueue {
// Block is run on the thread
}
在运行之前,会将代码块从队列中移除。
开始和取消线程的生命周期
// Initialize unstarted
let thread = Thread(start: false)
thread.enqueue {
// ...
}
thread.enqueue {
// ...
}
// Start the thread to begin running queued up blocks
thread.start()
// and maybe stop the thread again. Blocks still in the queue
thread.cancel()
暂停和恢复
let thread = Thread()
thread.enqueue {
// ...
}
// Pause
thread.pause()
// ... do other stuff
thread.enqueue {
//...
}
// Begin running blocks from queue again
thread.resume()
清空队列
// Remove any blocks still in queue
thread.emptyQueue()
清空队列
// Remove any blocks still in queue
thread.emptyQueue()
对于需要在背景线程上执行并在主线程上返回的任务,请使用出色的Async包装器,该包装器针对GCD。
MIT许可协议(MIT)
版权所有 © 2015 Tobias Due Munk
任何人可以免费获得此软件及其相关文档的副本(“软件”),用于在软件上无限制地处理,包括但不限于使用、复制、修改、合并、发布、分发、许可和/或出售软件的副本,以及授权获取软件副本的人这样做,前提是满足以下条件
上述版权声明和本许可声明应包含在软件的副本或主要内容中。
本软件按“原样”提供,不提供任何保证,无论明示还是默示,包括但不限于对适销性、特定用途适用性和非侵权的保证。在任何情况下,作者或版权所有者均不对任何索赔、损害或其他责任负责,无论行使合同行为、侵权行为或其他行为,由软件或其使用或其他操作而产生。