我正在对存储在磁盘上的同一资源执行多个读取操作。
有时,读取操作本身比对同一资源的请求之间的时间要长。在这些情况下,将读取操作批量处理为来自磁盘的一个读取请求,然后将相同的结果返回给各个请求者是有意义的。
最初我尝试缓存来自初始获取资源请求的结果 - 但这不起作用,因为读取资源所花费的时间太长,并且新请求进来 - 这意味着他们也会尝试获取资源。
是否可以将附加请求“附加”到已经在进行中的请求?
我现在拥有的代码遵循这个基本结构(这还不够好):
-(void)fileForKey:(NSString *)key completion:(void(^)(NSData *data) {
NSData *data = [self.cache threadSafeObjectForKey:key];
if (data) {
// resource is cached - so return it - no need to read from the disk
completion(data);
return;
}
// need to read the resource from disk
dispatch_async(self.resourceFetchQueue, ^{
// this could happen multiple times for the same key - because it could take a long time to fetch the resource - all the completion handlers should wait for the resource that is fetched the first time
NSData *fetchedData = [self fetchResourceForKey:key];
[self.cache threadSafeSetObject:fetchedData forKey:key];
dispatch_async(self.completionQueue, ^{
completion(fetchedData);
return;
});
});
}