Using code like the code below, will the new thread created end on its own after the function returns?
new Thread(() =>
{
function();
}).Start();
I'm pretty new to threading, so I wondered.
A thread is automatically destroyed when the run() method has completed. But it might be required to kill/stop a thread before it has completed its life cycle. Previously, methods suspend(), resume() and stop() were used to manage the execution of threads.
A thread automatically terminates when it returns from its entry-point routine. A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation.
When you kill process, everything that process owns, including threads is also killed. The Terminated property is irrelevant. The system just kills everything.
You can start a thread like: Thread thread=new Thread(new Runnable() { @Override public void run() { try { //Do you task }catch (Exception ex){ ex. printStackTrace();} } }); thread. start(); To stop a Thread: thread.
That's fine... if it's a concern that the Thread might not complete before your executable quits, you might want:
new Thread(() =>
{
function();
}){IsBackground = true}.Start();
Background threads will not prevent your app from exiting.
Yes, the thread will end after the function completes, but unless you have a parameter you need to use inside the function I wouldn't start it like that; I would just do:
new Thread(function).Start();
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