I want to have the main thread spawn threads and be able to keep spawning more with out waiting for all of the threads to finish. The spawning of the threads is user controlled, so the user could add at different periods of time more threads.
The thing is… how can I do this, when the main thread is running the finalize. In the finalize make it wait until all active threads have finished.
Keep track of all your created threads; for example, through a
List<Thread>collection. When you’re in yourfinalizemethod, just iterate over all your threads and call theirJoinmethod sequentially, as shown in theWaitForThreadsmethod below:Thread.Joinblocks the calling thread (which should be your main thread) until the specific thread terminates. If the thread was already terminated, then the call would return immediately (which is why you don’t really need to remove threads from the collection upon termination, although you still should for the sake of garbage collection).Also, you should consider why you need to wait for the threads to terminate within your
finalizemethod. If it’s simply to prevent them from being forcibly aborted when your main thread terminates, then there’s no need; your process would remain alive (even without a window) until all threads whoseIsBackgroundproperty isfalsefinish executing. Similarly for garbage collection; your heap objects will not get finalized until they’re no longer referenced from any live thread, not just the main.