Pseudo-situation: have a class (let's say BackgroundMagic
), and it has Start()
and Stop()
methods. The work in this class is done by one single thread, and is simply a short loop every X milliseconds.
Which of these options is better, as far as managing the stopping/starting? Can't decide which road to take.
IsBackground
= true. Use a simple bool flag to indicate on each loop around whether it should actually do any work, or just sleep. After initial initialization, let Stop() and Start() simply control the bool flag. The thread will just be stopped and cleaned up by the runtime since IsBackground
= true when the app exits.... or any better/cleaner ways of doing this?
Neither! Use a Thread Pool!
Thread creation is fairly expensive, so the standard "industrial-strength" way to do this is to control the thread with a flag. For a larger-scale variant on the same idea, consider the thread pools that e.g. Apache uses to manage thousands of threads without a lot of explicit state or a painful performance hit.
So in the abstract, I'd vote for your option #1. But if performance isn't a concern and the option #2 code is easier to reason about, go for it.
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