gpt4 book ai didi

ios - NSOperationQueue : cancel an operation after a timeout given

转载 作者:可可西里 更新时间:2023-11-01 06:24:31 26 4
gpt4 key购买 nike

基本上,如果我添加到队列的操作在特定超时后没有响应,我想执行取消:

NSOperationQueue *   queue = ...

[self.queue addOperationWithBlock:^{
// my block...
} timeoutInSeconds:5.0 hasTimedOutWithBlock:^{
// called after 5.0, operation should be canceled at the end
}];

谢谢大家!

最佳答案

你可以按照你的要求做一些事情,但我可能建议向第一个 block 添加一个参数,第一个 block 可以通过该参数检查操作是否被取消。

[queue addOperationWithBlock:^(NSOperation *operation) {

// do something slow and synchronous here,

// if this consists of a loop, check (and act upon) `[operation isCancelled]` periodically

} timeout:5.0 timeoutBlock:^{

// what else to do when the timeout occurred

}];

也许您不需要检查 isCancelled,但在某些情况下您会(通常响应取消的负担取决于操作本身),因此添加这可能是一个谨慎的参数.

无论如何,如果那是您想要的,您可以执行如下操作:

@implementation NSOperationQueue (Timeout)

- (NSOperation *)addOperationWithBlock:(void (^)(NSOperation *operation))block timeout:(CGFloat)timeout timeoutBlock:(void (^)(void))timeoutBlock
{
NSBlockOperation *blockOperation = [[NSBlockOperation alloc] init]; // create operation
NSBlockOperation __weak *weakOperation = blockOperation; // prevent strong reference cycle

// add call to caller's provided block, passing it a reference to this `operation`
// so the caller can check to see if the operation was canceled (i.e. if it timed out)

[blockOperation addExecutionBlock:^{
block(weakOperation);
}];

// add the operation to this queue

[self addOperation:blockOperation];

// if unfinished after `timeout`, cancel it and call `timeoutBlock`

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(timeout * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// if still in existence, and unfinished, then cancel it and call `timeoutBlock`

if (weakOperation && ![weakOperation isFinished]) {
[weakOperation cancel];
if (timeoutBlock) {
timeoutBlock();
}
}
});

return blockOperation;
}

@end

提供了该代码示例后,我必须承认,在极少数情况下,类似上述的内容可能会有用。一般来说,使用另一种模式会更好地解决这个问题。大多数时候,当你想要一个可取消的操作时,你会实现一个 NSOperation 子类(通常是一个并发的 NSOperation 子类)。请参阅 Operation Queues定义自定义操作对象部分Concurrency Programming Guide 章节以获取更多信息。

关于ios - NSOperationQueue : cancel an operation after a timeout given,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25474752/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com