如何在swift中取消多个线程之一
那么..我在这样的情况:我有一个function,启动3个asynchronous线程。 每个线程都需要一些时间。 当某个线程完成后,我需要停止另一个线程,但是我不知道如何去做。
我的代码:
class SomeController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. threads(); } func threads(){ let operationQueue = NSOperationQueue(); operationQueue.addOperationWithBlock( { let thread = NSThread.currentThread(); let threadNumber = thread.valueForKeyPath("private.seqNum").integerValue; NSThread.sleepForTimeInterval(30); println("Task #1 completed on thread #\(threadNumber)"); }) operationQueue.addOperationWithBlock( { let thread = NSThread.currentThread(); let threadNumber = thread.valueForKeyPath("private.seqNum").integerValue; NSThread.sleepForTimeInterval(20); println("Task #2 completed on thread #\(threadNumber)"); }) operationQueue.addOperationWithBlock( { let thread = NSThread.currentThread(); let threadNumber = thread.valueForKeyPath("private.seqNum").integerValue; NSThread.sleepForTimeInterval(5); println("Task #3 completed on thread #\(threadNumber)"); }) }}
任何迅速的帮助或build议将得到apperciated 🙂
这不是一个关于取消NSThread
的问题。 相反,这是一个如何取消NSOperation
。 在这种情况下,取消所有的操作是相对容易的,因为你只是为了执行你的三个块而创build一个NSOperationQueue
。 只要发送一个cancelAllOperations消息,
operationQueue.cancelAllOperations()
不幸的是,取消操作确实是合作的,所以在操作中你必须定期检查是否已isCancelled
并按要求终止:
var operation3:NSOperation? operation3 = operationQueue.addOperationWithBlock { let thread = NSThread.currentThread() let threadNumber = thread.valueForKeyPath("private.seqNum").integerValue var timeout = 5 while timeout-- > 0 && !operation3.isCancelled { NSThread.sleepForTimeInterval(1) } println("Task #3 completed on thread #\(threadNumber)") operationQueue.cancelAllOperations() }
如果使用addOperationWithBlock创build操作,则可以取消所有您喜欢的操作,但不起作用。 如果你想取消一个操作,我build议不要使用块,而是inheritanceNSOperation。 被执行的任务必须在取消任务时手动检查并完成任务; 你不能用addOperationWithBlock来做到这一点。
- AVPlayer锁屏控制
- 根据用户位置从Firebase附近按距离排列数组
- 获取UILabel中的每一行文本
- Swift 3.1:自定义错误转换为NSError来访问其属性时崩溃
- 如何处理同步错误:“收到错误的变更集:断言失败:left()。link_target_table_ndx == right()。link_target_table_ndx”
- 使用AVPlayer播放器控件中不显示Airplaybutton
- Firebase云消息传递不会创build推送通知,但会获取信息
- 单击第一个ViewController中的button,更改第二个ViewController的标签文本
- 迅速在不同的UnsafePointer <T>之间进行投射