Starting background work in a constructor is very poor design. That said there is absolutely nothing stopping your from just calling new without capturing the returned object.
new StartProcessX();
new StartProcessY();
vs
var A = new StartProcessX();
var B = new StartProcessY();
A better approach would be creating the objects and keeping references to them for either canceling the tasks or knowing when they are finished.
class Program {
private static StartProcessX _startProcessX;
private static StartProcessY _startProcessY;
public static Main {
_startProcessX = new StartProcessX;
_startProcessY = new StartProcessY;
_startProcessX.Start();
_startProcessY.Start();
// do something
while ( running ) {
}
Exit();
}
public static void Exit () {
_startProcessX.Cancel();
_startProcessY.Cancel();
}
}
Edit in response to comment below.
If that is too verbose then consider registering them. Perhaps this would better suite your situation.
abstract class Process {
abstract void Start();
abstract void Stop();
}
class Program {
private static Dictionary<Type, Process> Processes;
public static Main {
// Initialize all 40 objects
Processes = new Dictionary <Type, Process> () {
{ typeof(ProcessX), new ProcessX },
{ typeof(ProcessY), new ProcessY }
};
// Start them all. This could be moved to a function.
foreach ( var process in Processes ) {
process.Start();
}
while ( running ) {
}
// Stop or cancel a specific process by type.
Stop<ProcessX>();
// or stop all processes
foreach( var process in Processes ) {
process.Stop();
}
}
public static void Stop<T> () {
if ( Processes.TryGetValue ( typeof(T), out Process process) ) {
process.Stop();
}
}
}
Start()
method, inherit, keepList<BaseClass>
around. (Or just useTask
, as it seems that's what they are anyway.) "But I don't need them!" Oh, you will, even if only for debugging later. Objects that run off into the distance to do things in space, unreachable to anyone but the threads they've happened to spawn, are really not a good idea. – Jeroen Mostert Apr 10 '19 at 15:12