嗯..我的情况是这样的:我有一个启动3个异步线程的函数。每个线程都需要一些时间。当一些线程首先完成时,我需要它来阻止其他2,但我不知道该怎么做(还)。
我的代码:
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)");
})
}}
任何斯威夫特的帮助或建议都会被证实:)
答案 0 :(得分:3)
这不是关于取消NSThread
的问题。相反,这是一个如何取消NSOperation
的问题。在这种情况下,取消所有操作相对容易,因为您创建单个NSOperationQueue
仅用于执行三个块。只需向operationQueue发送一条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()
}
答案 1 :(得分:1)
如果使用addOperationWithBlock创建操作,则可以取消所有操作,但它无效。如果您想取消操作,我建议不要使用块,而是继承NSOperation。正在执行的任务必须在取消后手动检查并完成任务;你不能用addOperationWithBlock做到这一点。