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?
Yes, it is safe insofar as the thread will continue until completion by itself, you do not need to have a reference to the
Threadobject 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.