I have a thread which contains execution of an IronPython script. For some reason I may need to stop this thread at any time, including script execution. How to achieve this? The first idea is Thread.Abort()
, but it's known to be evil...
You can use pthread_cancel() to kill a thread: int pthread_cancel(pthread_t thread); Note that the thread might not get a chance to do necessary cleanups, for example, release a lock, free memory and so on..
Blocking a Thread: These methods cause the thread to go into the blocked (or not-runnable) state. The thread will return to the runnable state when the specified time is elapsed in the case of sleep( ), the resume() method is invoked in the case of suspend( ), and the notify( ) method is called in the case of wait().
Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds. The argument value for milliseconds can't be negative, else it throws IllegalArgumentException .
What is a safe way to stop a running thread?
Put the thread in its own process. When you want it to stop, kill the process.
That is the only safe way to kill a thread. Aborting a thread can severely destabilize a process and lose user data. There's no way to avoid the "lose user data" scenario if you really, truly need to be able to kill a thread that could be doing anything. The only way to avoid destabilizing the process that is calling for the abort is to make them different processes entirely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With