如何在只处理最新请求的iOS中实现工作队列?

时间:2012-11-05 13:00:24

标签: objective-c ios concurrency

在我的iOS程序中会发生以下情况:当用户键入时,会向启动数据库查找的线程触发请求。完成数据库查找后,将在主线程上触发响应,以便应用程序显示结果。

这很有效,但如果用户输入速度非常快,则可能会有多个请求在飞行中。最终系统会赶上,但效率似乎很低。

是否有一种巧妙的方法来实现它,以便在启动请求时,我可以检测到查询已在进行中,而请求应该存储为“可能最新的超过飞行中的那个”?

以下添加评论的示例解决方案

这是一个小型示例项目的视图控制器的主体,用于说明解决方案的属性。键入时,您可能会得到如下输出:

2012-11-11 11:50:20.595 TestNsOperation[1168:c07] Queueing with 'd'
2012-11-11 11:50:20.899 TestNsOperation[1168:c07] Queueing with 'de'
2012-11-11 11:50:21.147 TestNsOperation[1168:c07] Queueing with 'det'
2012-11-11 11:50:21.371 TestNsOperation[1168:c07] Queueing with 'dett'
2012-11-11 11:50:21.599 TestNsOperation[1168:1b03] Skipped as out of date with 'd'
2012-11-11 11:50:22.605 TestNsOperation[1168:c07] Up to date with 'dett'

在这种情况下,将跳过第一个排队的操作,因为它在执行其冗长的工作时确定它已经过时。以下两个排队操作('de'和'det')在被允许执行之前被取消。最后的最终操作是唯一一个真正完成所有工作的人。

如果您注释掉[self.lookupQueue cancelAllOperations]行,则会出现以下行为:

2012-11-11 11:55:56.454 TestNsOperation[1221:c07] Queueing with 'd'
2012-11-11 11:55:56.517 TestNsOperation[1221:c07] Queueing with 'de'
2012-11-11 11:55:56.668 TestNsOperation[1221:c07] Queueing with 'det'
2012-11-11 11:55:56.818 TestNsOperation[1221:c07] Queueing with 'dett'
2012-11-11 11:55:56.868 TestNsOperation[1221:c07] Queueing with 'dette'
2012-11-11 11:55:57.458 TestNsOperation[1221:1c03] Skipped as out of date with 'd'
2012-11-11 11:55:58.461 TestNsOperation[1221:4303] Skipped as out of date with 'de'
2012-11-11 11:55:59.464 TestNsOperation[1221:1c03] Skipped as out of date with 'det'
2012-11-11 11:56:00.467 TestNsOperation[1221:4303] Skipped as out of date with 'dett'
2012-11-11 11:56:01.470 TestNsOperation[1221:c07] Up to date with 'dette'

在这种情况下,所有排队的操作都将执行其工作的长度部分,即使在它被安排执行之前已将更新的操作排入其后。

@interface SGPTViewController ()

@property (nonatomic, strong) NSString* oldText;
@property (strong) NSOperationQueue *lookupQueue;

@end

@implementation SGPTViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.oldText = self.source.text;
    self.lookupQueue = [[NSOperationQueue alloc] init];
    self.lookupQueue.maxConcurrentOperationCount = 1;
}

- (void)textViewDidChange:(UITextView *)textView
{
    // avoid having a strong reference to self in the operation queue
    SGPTViewController * __weak blockSelf = self;

    // you can cancel existing operations here if you want
    [self.lookupQueue cancelAllOperations];

    NSString *outsideTextAsItWasWhenStarted = [NSString stringWithString:self.source.text];
    NSLog(@"Queueing with '%@'", outsideTextAsItWasWhenStarted);
    [self.lookupQueue addOperationWithBlock:^{
        // do stuff
        NSString *textAsItWasWhenStarted = [NSString stringWithString:outsideTextAsItWasWhenStarted];
        [NSThread sleepForTimeInterval:1.0];
        if (blockSelf.lookupQueue.operationCount == 1) {
            // do more stuff if there is only one operation on the queue,
            // i.e. this one. Operations are removed when they are completed or cancelled.
            // I should be canceled or up to date at this stage
            dispatch_sync(dispatch_get_main_queue(), ^{
                if (![textAsItWasWhenStarted isEqualToString:self.source.text]) {
                    NSLog(@"NOT up to date with '%@'", textAsItWasWhenStarted);
                } else {
                    NSLog(@"Up to date with '%@'", textAsItWasWhenStarted);
                }
            });
        } else {
            NSLog(@"Skipped as out of date with '%@'", textAsItWasWhenStarted);
        }
    }];
}

3 个答案:

答案 0 :(得分:5)

如果您的查询确实需要很长时间,我会想到一种机制,通过让我们说1来减慢查询,并取消先前的查询请求(如果有的话)。因此,如果您使用块,可能就是这样:

@interface YourViewController
   @property(assign) NSInteger currentTaskId; // atomic

...

@implementation YourViewController
@synthesize currentTaskId;
// your target method
- (void)textFieldDidChange
{
        self.currentTaskId = self.currentTaskId + 1;
        NSInteger taskId = self.currentTaskId;

        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), queue, ^{
            if (taskId == self.currentTaskId) // this is still current task
            {
                // your query

                if (taskId == self.currentTaskId) // sill current after query? update visual elements
                {
                    // your main thread updates
                }
            } // else - there is newer task so skip this old query 
        });
}

答案 1 :(得分:4)

我喜欢NSOperationQueue这样的情况。

@interface ClassName ()
...
// atomic since it does not specify nonatomic
@property (strong) NSOperationQueue *lookupQueue;
...
@end

- (id)init
{
    ...
    lookupQueue = [[NSOperationQueue alloc] init];
    lookupQueue.maxConcurrentOperationCount = 1;
    ...
}

- (void)textFieldDidChange
{
    // avoid having a strong reference to self in the operation queue
    ClassName * __weak blockSelf = self;

    // you can cancel existing operations here if you want
    // [lookupQueue cancelAllOperations];

    [lookupQueue addOperationWithBlock:^{
        // do stuff
        ...
        if (blockSelf.lookupQueue.operationCount == 1) {
            // do more stuff if there is only one operation on the queue,
            // i.e. this one. Operations are removed when they are completed or cancelled.
        }
    }];
}

编辑:只需注意,你需要使用[[NSOperationQueue mainQueue] addOperationWithBlock:]或类似的方法来更新GUI或运行必须在主线程上的任何其他代码,从block参数内部到[lookupQueue addOperationWithBlock: ]

答案 2 :(得分:1)

NSOperationQueue提供了一种方法-cancelAllOperations。因此,在添加操作时,如果操作已在运行,则调用它。问题的其余部分是你的NSOperation子类必须定期检查它是否已被取消(并停止doin',在那种情况下)。该检查位于您的-main

的覆盖中