简体   繁体   中英

cancel a background thread in Objective-C

How do I cancel a background thread in Objective-C?

I am calling background threads like so:

[self performSelectorInBackground:@selector(setupThumbnails) withObject:nil];

It is called when a swipe happens, for each swipe I want to cancel the previous background thread request.

Maintain a cancellation property for your thread, and check it periodically within your thread. You'll need to either use a lock or atomic function (as provided by the operating system and its frameworks, not implemented yourself!) to indicate the thread should be cancelled. The system-provided atomic functions are documented in the atomic manpage.

Even better would be to use NSOperation on an NSOperationQueue instead of NSThread. It will still perform work in the background using a thread, but it lets the framework and operating system manage a thread pool on your behalf, and NSOperation itself has an isCancelled property you can check - as well as the ability to cancel either an individual NSOperation or all operations in an entire NSOperationQueue.

For example, you could have a "set up one thumbnail" operation, and then just add one such operation to a queue for each thumbnail to set up. The OS and framework will cooperate to manage the number of threads used to execute those operations, though you could also set the queue's width to ensure only at most that many imports run at once. And if the user cancels, you can just ask the queue to cancel all the outstanding operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM