Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to kill a thread written like this? Or will it automatically end?

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.

like image 880
PhoenixLament Avatar asked Mar 17 '13 15:03

PhoenixLament


People also ask

Does a thread automatically be killed?

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.

How do you terminate a thread?

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.

Does killing a process kill all threads?

When you kill process, everything that process owns, including threads is also killed. The Terminated property is irrelevant. The system just kills everything.

How do we start and stop a thread?

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.


Video Answer


2 Answers

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.

like image 98
spender Avatar answered Nov 07 '22 04:11

spender


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();
like image 43
Naate Avatar answered Nov 07 '22 05:11

Naate