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?
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.
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.
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.
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.
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.
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