Created
October 29, 2013 04:17
-
-
Save jwilling/7209108 to your computer and use it in GitHub Desktop.
Simple block-based serial queue for asynchronous operations.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// QTMAsyncOperationQueue.h | |
// Quantum | |
// | |
// Created by Jonathan Willing on 10/28/13. | |
// Copyright (c) 2013 AppJon. All rights reserved. | |
// | |
#import <Foundation/Foundation.h> | |
typedef void (^QTMAsyncOperationQueueCompletion)(); | |
@interface QTMAsyncOperationQueue : NSObject | |
/// The queue on which the operations are dispatched. | |
/// | |
/// Defaults to the main queue. | |
@property (nonatomic, assign) dispatch_queue_t dispatchQueue; | |
/// Adds an asynchronous operation to the queue. The operation will only be started when any | |
/// previously-enqueued operations have completed (serially). | |
/// | |
/// The operations themselves be dispatched on `dispatchQueue`, which defaults to the main queue. | |
/// | |
/// The completion block must be fired by the caller to signify the completion of the async operation. | |
- (void)addAsynchronousOperation:(void (^)(QTMAsyncOperationQueueCompletion completion))operation; | |
@end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// QTMAsyncOperationQueue.m | |
// Quantum | |
// | |
// Created by Jonathan Willing on 10/28/13. | |
// Copyright (c) 2013 AppJon. All rights reserved. | |
// | |
#import "QTMAsyncOperationQueue.h" | |
@interface QTMAsyncOperationQueue() | |
@property (nonatomic, strong) dispatch_group_t internalDispatchGroup; | |
@property (nonatomic, strong) dispatch_queue_t internalDispatchQueue; | |
@end | |
@implementation QTMAsyncOperationQueue | |
- (instancetype)init { | |
self = [super init]; | |
if (self == nil) return nil; | |
self.dispatchQueue = dispatch_get_main_queue(); | |
self.internalDispatchQueue = dispatch_queue_create("com.appjon.asyncOperationQueue", DISPATCH_QUEUE_SERIAL); | |
self.internalDispatchGroup = dispatch_group_create(); | |
return self; | |
} | |
- (void)addAsynchronousOperation:(void (^)(QTMAsyncOperationQueueCompletion))operation { | |
dispatch_async(self.internalDispatchQueue, ^{ | |
dispatch_group_enter(self.internalDispatchGroup); | |
void (^completion)() = ^{ | |
dispatch_group_leave(self.internalDispatchGroup); | |
}; | |
dispatch_async(self.dispatchQueue, ^{ | |
operation(completion); | |
}); | |
dispatch_group_wait(self.internalDispatchGroup, DISPATCH_TIME_FOREVER); | |
}); | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment