Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

consequences of not calling Thread.Join()

Tags:

c#

.net

If I spin up a new thread in C#, can I just fire and forget without worrying about the thread being joined?

void DoSomething()
{
  var worker = new Worker();
  var start = new ThreadStart(worker.DoStuff);
  var thread = new Thread(start);
  thread.Start();

  // do something else...
  // who knows how long it'll take...

  // exit without calling thread.Join()

}

Are there consequences to writing this code?

like image 214
kindohm Avatar asked Jun 15 '11 20:06

kindohm


People also ask

What happens if you dont call thread join?

If you don't join these threads, you might end up using more resources than there are concurrent tasks, making it harder to measure the load. To be clear, if you don't call join , the thread will complete at some point anyway, it won't leak or anything.

Do you have to call thread join?

Not necessarily - depends on your design and OS. Join() is actively hazardous in GUI apps - tend If you don't need to know, or don't care, about knowing if one thread has terminated from another thread, you don't need to join it.

What happens if you don't join a thread Python?

A Python thread is just a regular OS thread. If you don't join it, it still keeps running concurrently with the current thread. It will eventually die, when the target function completes or raises an exception.

Why do we need thread join?

Join is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated. The caller will block indefinitely if the thread does not terminate.


1 Answers

Yes, it is safe insofar as the thread will continue until completion by itself, you do not need to have a reference to the Thread object to keep it alive, nor will the behavior of the thread change in any way.

The only thing you give up is the ability to later on join on the thread, or check its status, but it is absolutely safe to fire and forget threads.

However, if you fire and forget a thread set as a background thread, that thread might not run to completion if the program exits before the thread completes.

like image 189
Lasse V. Karlsen Avatar answered Oct 20 '22 03:10

Lasse V. Karlsen