Re: sending msgs to nsoperation threads
Re: sending msgs to nsoperation threads
- Subject: Re: sending msgs to nsoperation threads
- From: Andreas Grosam <email@hidden>
- Date: Thu, 11 Nov 2010 09:48:52 +0100
On Nov 11, 2010, at 8:13 AM, Shane wrote:
> I've got an NSOperation thread running, but I'd like to be able to
> send a message to it so that the thread can be shut it down, or
> possibly other commands.
>
> What is considered a good way to send a message to an NSOperation
> thread from the apps main thread?
Usually, NSOperation objects execute on threads managed by the corresponding NSOperationQueue where you added them, e.g.:
MyOperation* op = [[MyOperation alloc] initWithMyParams:params];
[self.myOperationQueue addOperation op];
So, whatever operation queue you use, the *operation queue* is responsible for managing the threads your operation will execute on. The operation queue hides the complexity to create and destroy the threads - which is a good thing. Which threads the operation queue creates and when is a private thing to the operation queue. So, you should not bother with this.
Note, that there is a global queue [NSOperationQueue mainQueue] which executes its operations on the main thread.
In order to cancel an *operation* (not a thread) you can send the operation object the -cancel message from any other execution context. All what is required is to design the method -main of your operation such that it periodically checks whether it has been cancelled, e.g.:
- (void) main {
if ([self isCancelled])
return;
BOOL done = NO;
while (!done) {
// do a peace of work
// ...
if ([self isCancelled]) {
// optionally send the "delegate" a notification about the cancellation.
return;
}
}
// send the "delegate" a message about the result of the operation
}
Note: "delegate" is defined in your custom Operation.
When you send (custom) messages to an operation, you should care about proper synchronization if necessary.
see also:
NSOperationQueue: -cancelAllOperations
NSOperation: -cancel
NSOperation: "Responding to the Cancel Command"
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html
http://developer.apple.com/cocoa/managingconcurrency.html
Have fun!
Andreas
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden