synchronize background jobs in UIImageView
I have an interface defined like this
@interface PageViewController : UIImageView {
...
}
-(void) setImageUsing:(id) obj;
@end
and implementation is like the following
-(void) setImageUsing:(id) obj
{
...
[self performSelectorInBackground:@selector(changeImage) withObject:nil];
}
setImageUsing
is called from other code as result of user interactions with the application.
How should I proceed to limit PageViewController
to only one background job at a time?
In other words, I would like to cancel any running background job when a new call to setImageUsing
is made and start a new background job after that.
EDIT/SOLUTION:
As Ishu proposed, I tried to use NSLock for synchronization purposes. The final code (that solved the issue) looks like this:
@interface PageViewController : UIImageView {
...
NSLock* m_threadLock;
NSLock* m_externalLock;
BOOL m_cancelThread;
}
-(void) setImageUsing:(id) obj;
@end
and implementation is like the following
-(void) setImageUsing:(id) obj
{
[m_externalLock lock];
...
if ([m_threadLock tryLock])
{
// succeeded in locking thread lock. so there is no background job running.
// unlock the lock and continue
[m_threadLock unlock];
}
else
{
// failed to lock thread lock. so there IS a job already running.
// ask the job to cancel
m_cancelThread = YES;
}
[self performSelectorInBackground:@selector(changeImage) withObject:nil];
[m_externalLock unlock];
}
-(void) changeImage
{
[m_threadLock lock];
....
开发者_如何学C if (m_cancelThread)
{
// cancel
}
...
m_cancelThread = NO;
[m_threadLock unlock];
}
Hope it'll help someone else.
This is not good way to terminate any background task , competing the background thread execution is good see this thread. What you need , you need to lock an thread allocation for some kind of mishappenings. See NSLocks in developer documentation and some googling gives you some info about NSLock.
精彩评论