Dmitry
Dmitry

Reputation: 14632

How to terminate performSelectorInBackground: thread?

How can I kill a thread created by performSelectorInBackground:withObject: from the main thread? I need to force termination of freezing threads.

Upvotes: 3

Views: 3642

Answers (3)

ThE uSeFuL
ThE uSeFuL

Reputation: 1534

Apple documentation says

The recommended way to exit a thread is to let it exit its entry point routine normally. Although Cocoa, POSIX, and Multiprocessing Services offer routines for killing threads directly, the use of such routines is strongly discouraged. Killing a thread prevents that thread from cleaning up after itself. Memory allocated by the thread could potentially be leaked and any other resources currently in use by the thread might not be cleaned up properly, creating potential problems later.

Upvotes: 0

omz
omz

Reputation: 53561

You cannot kill background threads from the main thread, the method that is executing in a background thread has to return for the thread to end.

Your actual problem seems to be that your background thread is freezing, you should solve that instead of trying to work around it.

Upvotes: 9

Sid
Sid

Reputation: 9536

I'm not sure if this may help but here goes:

Assuming you're calling that performSelector call from class A. And assuming that class A is about to be released from memory in class B (which is where if the selector hasn't been performed yet, you might be getting a crash - Hence you're posting this question on SO):

Wherever you're releasing A from B, do this:

[NSObject cancelPreviousPerformRequestsWithTarget:A];

Upvotes: 0

Related Questions