AsyncTask implementation using NSOperation in iOS - ios

I implemented AsyncTask(Android) in iOS using NSOperation subclass.
-(id)initWithParam:(NSArray *)params{
if (self = [super init]) {
paramsArray = params;
}
return self;
}
- (void)start {
#autoreleasepool {
if (self.isCancelled)
return;
NSInteger result;
result = [self doInBackground:paramsArray];
dispatch_async(dispatch_get_main_queue(), ^{
[self postExecute:result];
});
}
}
- (BOOL) doInBackground: (NSArray *) parameters{
BOOL status = false;
int i;
for (i=0; i<100000; i++) {
NSLog(#"printing i::%d",i);
}
if (i == 100000) {
status = YES;
}
return status;
}
- (void) postExecute: (BOOL) deviceState{
if (deviceState) {
NSLog(#"Finished");
}
}
-(BOOL)isConcurrent{
return YES;
}
This is the way I implemented in iOS.Please suggest and any thing I want to add for this functionality.
And also, when can I call isExecuting and isFinished in NSOperation subclass

In answer to your question, unfortunately, no, this implementation is not correct. Close, but not quite there.
A couple of things:
Your example is not concurrent operation. In the case of NSOperation, the term "concurrent operation" (now called an "asynchronous operation") has a special meaning. An asynchronous operation is one that that continues to run asynchronously even after the start method finishes. And you designate this by returning YES from isConcurrent (in older iOS versions) and isAsynchronous (in contemporary iOS versions). But the example operation in the question is completely done when start ends, so therefore is not an asynchronous operation and therefore isConcurrent and isAsynchronous should therefore return NO.
Let's assume in this example that you changed isConcurrent to return NO, as would be appropriate with what you're performing in start. That would fix this operation. But don't let this confuse you. If you added this operation to your own operation queue, it would still run asynchronously/concurrently with respect to the main queue, it's just that it's an operation that automatically finishes when start finishes, and therefore isAsynchronous/isConcurrent should return NO.
You ask "when can I call isExecuting and isFinished?" Well, you generally don't call those methods. You generally implement those methods. Specifically, when an asynchronous operation eventually finishes, you must ensure that the app (a) posts KVN for the isExecuting and isFinished keys; and (b) you override isExecuting and isFinished to ensure that they correspondingly return the appropriate values.
You only have to implement this isExecuting and isFinished code when the operation is truly an asynchronous/concurrent operation. See the Configuring Operations for Concurrent Execution section of the Concurrency Programming Guide: Operation Queues. Also see the introductory section of the NSOperation class definition.
Whether your operation should be asynchronous or not (or even whether you need to subclass NSOperation at all) is unclear. It depends entirely upon what task you want to perform, and whether the task itself runs asynchronously or not.

Related

why use "willChangeValueForKey:" in SDWebImage?

There is a class named "SDWebImageDownloaderOperation" which has the following method in SDWebImageView lib.
- (void)setFinished:(BOOL)finished {
[self willChangeValueForKey:#"isFinished"];
_finished = finished;
[self didChangeValueForKey:#"isFinished"];
}
however, rs does not override automaticallyNotifiesObserversForKey: and don't implement observeValueForKeyPath:ofObject:change:context: methods,so what is the purpose of writing
[self willChangeValueForKey:#"isFinished"]
and
[self didChangeValueForKey:#"isFinished"]
The key reason here is that SDWebImageDownloaderOperation is a subclass of NSOperation and this class doesn't work with normal KVO notification like all the other classes.
This operation performs some task on background, so you need to inform the operating system when your operation is finished and when is still running.
Apple suggests here to explicitly call willChangeValueForKey and didChangeValueForKey.
If you are looking for a better explanation why NSOPerations don't have normal KVO you can read this answer Why does NSOperation disable automatic key-value observing?

How do I wait for a method to finish before calling it again?

I am building a simple messaging app using Parse's framework. I have a method called displayMessages. This is called each time the phone receives a push.
However, as this message is doing work in the Parse database I don't want to call it again if it's already running. I want to wait until it is finished and then call it.
I am using the following code:
-(void)receivedPush
{
[self displayMessages];
}
and:
-(void)displayMessages
{
//code here
}
If received push is called I want it to wait until displayMessages is finished before calling it. Could someone please point me in the right direction with this?
UPDATE
I tried using the NSOperationQueue method and realised that although this does work for waiting for displayMessages it doesn't result in the required behavior.
In displayMessages I have: [PFObject deleteAllInBackground:toDelete]; it's actually this I need to wait for completion before calling displayMessages again.
Create a NSOperationQueue and set the maxConcurrentOperationCount to 1. Implement your data access method as an operation (possibly block-type operation) and submit it to the queue. (I like this better than gcd since you can do cancellation or test the number of items already in the queue.)
Note that if the method actually displays things, you'll need to dispatch back to the main queue for UI work.
You could use a NSOperationQueue with maxConcurrentOperationCount set to 1.
Declare the NSOperationQueue as an iVar of your class, initialize it in the init method and set
[_opQueue setMaxConcurrentOperationCount:1];
and then when you receive the push:
- (void)receivedPush {
NSInvocationOperation *op = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(displayMessages) object:nil];
[_opQueue addOperation:op];
}
Shortest and simples would be creating BOOL isExecuting and checking if you can call method based on that (changing values before execution but after check and after execution)
How about this for a fairly lightweight solution:
#property (nonatomic, assign) BOOL needsToDisplayMessages;
#property (nonatomic, assign) BOOL displayingMessages;
Then
-(void)receivedPush
{
if (!self.displayingMessages) {
[self displayMessages];
} else {
self.needsToDisplayMessages = YES;
}
}
-(void)displayMessages
{
self.needsToDisplayMessages = NO;
self.displayingMessages = YES;
//long-running code here
self.displayingMessages = NO;
if (self.needsToDisplayMessages) {
[self displayMessages]
}
(ignoring concurrency issues ... for which you could use GCD in displayMessages or NSOperationQueue as per a couple of the other answers)
With your new updated requirement, you can use deleteAllInBackground:block:. According to document:
"Deletes a collection of objects all at once asynchronously and executes the block when done."
Why not schedule each message handling using:
-(void)receivedPush
{
dispatch_async(dispatch_get_main_queue(), ^{
/* Show the update on the display */
NSLog(#"Handling new messages");
NSArray *newMessages=<populate with new messages>;
[handler displayMessages:newMessages];
});
}
This will queue up your handling of each set as they come in. Only one displayMessages will run at a time.

NSOperationQueue : cancel an operation after a timeout given

Basically, I would like to perform a cancel if the operation I'm adding to the queue does not respond after a certain timeout :
NSOperationQueue * queue = ...
[self.queue addOperationWithBlock:^{
// my block...
} timeoutInSeconds:5.0 hasTimedOutWithBlock:^{
// called after 5.0, operation should be canceled at the end
}];
Thanks Guys !
You could do something like you asked for, but I might suggest adding a parameter to the first block by which the first block could check to see if the operation was canceled.
[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
}];
Maybe you don't need to check isCancelled, but in some cases you would (generally the burden for responding to a cancellation rests on the operation itself), so that's probably a prudent parameter to add.
Anyway, if that's what you wanted, you might do something like the following:
#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
Having provided that code sample, I must confess that there are a very narrow set of situations where something like the above might be useful. Generally it would be better addressed using another pattern. The vast majority of the time, when you want a cancelable operation, you would implement a NSOperation subclass (often a concurrent NSOperation subclass). See the Defining a Custom Operation Object section of the Operation Queues chapter of the Concurrency Programming Guide for more information.

How to dispatch code blocks to the same thread in iOS?

Main aspect of the question: It's about iOS. Can I somehow dispatch code blocks in a way, that they will all (a) run in background and (b) on the same thread? I want to run some time-consuming operations in background, but these have to be run on the same thread, because they involve resources, that mustn't be shared among threads.
Further technical details, if required: It's about implementing an sqlite plugin for Apache Cordova, a framework for HTML5 apps on mobile platforms. This plugin should be an implementation of WebSQL in the means of the Cordova's plugin API. (That means, it's not possible to wrap entire transactions within single blocks, what could make everything easier.)
Here is some code from Cordova's Docs:
- (void)myPluginMethod:(CDVInvokedUrlCommand*)command
{
// Check command.arguments here.
[self.commandDelegate runInBackground:^{
NSString* payload = nil;
// Some blocking logic...
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:payload];
// The sendPluginResult method is thread-safe.
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
But as far as I know, there is no guarantee, that those dispatched code blocks (see runInBackground) will run on the same thread.
GCD makes no guarantee that two blocks run on the same thread, even if they belong to the same queue (with the exception of the main queue, of course). However, if you're using a serial queue (DISPATCH_QUEUE_SERIAL) this isn't a problem as you then know that there is no concurrent access to your data.
The man page for dispatch_queue_create says:
Queues are not bound to any specific thread of execution and blocks submitted to independent queues may execute concurrently.
I'm not aware of any way to bind a queue to a specific thread (after all, not needing to care about threads is a major point of GCD). The reason why you can use a serial queue without worrying about the actual thread is this promise:
All memory writes performed by a block dispatched to a serial queue are guaranteed to be visible to subsequent blocks dispatched to the same queue.
That is, a memory barrier seems to be used.
When dealing with threading issues, your main concern is usually to avoid that two threads access something concurrently. If you're using a serial queue you do not have this problem. It usually doesn't really matter which thread is accessing your resources. For example, we're using serial queues to manage Core Data access without a problem.
Edit:
It seems you really found a rare case where you need to be working on the same thread. You could implement your own worker thread:
Prerequisites:
A NSMutableArray (let's call it blockQueue).
A NSCondition (let's call it queueCondition).
Create a new NSThread.
The thread's method has an endless loop in which it locks the condition, waits for it if the queue is empty (and the "quit" bool is false), dequeues a block and executes it.
A method that locks the condition an enqueues the block.
Due to the condition, the thread will simply sleep while there's no work to do.
So, roughly (untested, assuming ARC):
- (void)startWorkerThread
{
workerThread = [[NSThread alloc]
initWithTarget:self
selector:#selector(threadMain)
object:nil
];
[workerThread start];
}
- (void)threadMain
{
void (^block)();
NSThread *currentThread;
currentThread = [NSThread currentThread];
while (1) {
[queueCondition lock];
{
while ([blockQueue count] == 0 && ![currentThread isCancelled]) {
[queueCondition wait];
}
if ([currentThread isCancelled]) {
[queueCondition unlock];
return;
}
block = [blockQueue objectAtIndex:0];
[blockQueue removeObjectAtIndex:0];
}
[queueCondition unlock];
// Execute block outside the condition, since it's also a lock!
// We want to give other threads the possibility to enqueue
// a new block while we're executing a block.
block();
}
}
- (void)enqueue:(void(^)())block
{
[queueCondition lock];
{
// Copy the block! IIRC you'll get strange things or
// even crashes if you don't.
[blockQueue addObject:[block copy]];
[queueCondition signal];
}
[queueCondition unlock];
}
- (void)stopThread
{
[queueCondition lock];
{
[workerThread cancel];
[queueCondition signal];
}
[queueCondition unlock];
}
Untested Swift 5 port:
var workerThread: Thread?
var blockQueue = [() -> Void]()
let queueCondition = NSCondition()
func startWorkerThread() {
workerThread = Thread() {
let currentThread = Thread.current
while true {
self.queueCondition.lock()
while self.blockQueue.isEmpty && !currentThread.isCancelled {
self.queueCondition.wait()
}
if currentThread.isCancelled {
self.queueCondition.unlock()
return
}
let block = self.blockQueue.remove(at: 0)
self.queueCondition.unlock()
// Execute block outside the condition, since it's also a lock!
// We want to give other threads the possibility to enqueue
// a new block while we're executing a block.
block()
}
}
workerThread?.start()
}
func enqueue(_ block: #escaping () -> Void) {
queueCondition.lock()
blockQueue.append(block)
queueCondition.signal()
queueCondition.unlock()
}
func stopThread() {
queueCondition.lock()
workerThread?.cancel()
queueCondition.signal()
queueCondition.unlock()
}
In GCD: no, that's not possible with the current lib dispatch.
Blocks can be executed by dispatch lib on whatever thread which is available, no matter to which queue they have been dispatched.
One exception is the main queue, which always executes its blocks on the main thread.
Please file a feature request to Apple, since it seems justified and sound. But I fear it's not feasible, otherwise it would already exist ;)
You can use NSOperationQueue. You can make it use just one thread by using method - (void)setMaxConcurrentOperationCount:(NSInteger)count. Set it to 1
Create a serial dispatch queue, and dispatch all the calls to that serial dispatch queue. All the calls will be performed in the background, but sequentially on the same thread.
If you want to perform a selector in Main Thread, you can use
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
and if you want to it to perform in background thread
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)object
and if you want to perform in any other thread use GCD(Grand Central Dispatch)
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//code to be executed on the main queue after delay
});
You can either use NSOperationQueue with a MaxConcurrentOperationCount of 1 or go the manual way down the road by using NSThread model (rather than Grand Central Dispatch).
Using the latter I would recommend you to implement a worker-method which runs in a thread and pulls work-packages (or commands) from a queue or a pool that is being feed from outside of the thread. Just make sure you use Locks / Mutex / Synchronisation.
Never tried this but this might do the trick. Use separate properties of atomic dispatch queues for each operation.
#property (strong, atomic) dispatch_queue_t downloadQueue;
Queue/Thread 1 for first operation
downloadQueue = dispatch_queue_create("operation1", NULL);
etc.
Since atomic is thread safe, downloadQueue should not be accessed by other threads. So it makes sure that there will be only single thread per operation and other threads will not access it.
Just like this,
dispatch_asyn(dispatch_get_current_queue, ^ {
});

Suggestions on making this threadsafe, yet efficient?

I have been thinking about a problem that seemingly would be simple to implement, yet an efficient and threadsafe solution is stymying me. What I want to do is create some sort of worker object. Several callers may ask it to work from different threads. A requirement is that requests must not queue up. In other words if somebody asks the worker to do work but sees it is already doing work, it should just return early.
A simple first pass is this:
#interface Worker : NSObject
#property (nonatomic, assign, getter = isWorking) BOOL working;
- (void)doWork;
#end
#implementation Worker
{
dispatch_queue_t _workerQueue; //... a private serial queue
}
- (void)doWork
{
if ( self.isWorking )
{
return;
}
self.working = YES;
dispatch_async(_workerQueue, ^{
// Do time consuming work here ... Done!
self.working = NO;
});
}
#end
The problem with this is that the isWorking property is not threadsafe. Marking it atomic won't help here, as accesses to it need to be synchronized across a few statements.
To make it threadsafe I would need to protect the isWorking with a lock:
#interface Worker : NSObject
#property (nonatomic, assign, getter = isWorking) BOOL working;
- (void)doWork;
#end
#implementation Worker
{
dispatch_queue_t _workerQueue; //... a private serial queue
NSLock *_lock; // assume this is created
}
- (void)doWork
{
[_lock lock];
if ( self.isWorking )
{
[_lock unlock];
return;
}
self.working = YES;
[_lock unlock];
dispatch_async(_workerQueue, ^{
// Do time consuming work here ... Done!
[_lock lock];
self.working = NO;
[_lock unlock];
});
}
#end
While I do believe this would be threadsafe, I think it's pretty crummy to have to take and give up a lock (an expensive operation) so frequently.
So, is there a more elegant solution?
dispatch_semaphore is the idiomatic way to limit access to a finite resource, if you're already using GCD.
// Add an ivar:
dispatch_semaphore_t _semaphore;
// To initialize:
_semaphore = dispatch_semaphore_create(1);
// To "do work" from any thread:
- (void)doWork
{
if (dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_NOW) == 0) {
// We got the semaphore without waiting, so we're first in line.
dispatch_async(_workerQueue, ^{
// do time consuming work here, then when done:
dispatch_semaphore_signal(_semaphore);
});
} else {
// We would have had to wait for the semaphore, so somebody must have
// been doing work already, and we should do nothing.
}
}
Here's a blog post explaining in more detail.
You may be able to use an atomic test-and-set operation here. GCC provides __atomic_test_and_set for this purpose. Here's how you might use it in C (untested):
static volatile bool working = FALSE;
if(__atomic_test_and_set(&working, __ATOMIC_ACQUIRE)) {
// Already was working.
}else{
// Do work, possibly in another thread.
// When done:
__atomic_clear(&working, __ATOMIC_RELEASE);
}
Easy, huh?
For making a property thread-safe you could simply use #synchronize.

Resources