Home > Back-end >  How to call Start() method of multiple thread class instances in one statement?
How to call Start() method of multiple thread class instances in one statement?

Time:10-16

Need syntax help, is there any way of calling the same method of multiple instances in one statement, like the way we assign values to multiple variables?

var t1 = new Thread(SayHello);
var t2 = new Thread(SayHello);
var t3 = new Thread(SayHello);

(t1.Name, t2.Name, t3.Name) = ("Thread1", "Thread2", "Thread3");

// any way to call t1,t2, and t3's Start Method in one statement like above
t1.Start();
t2.Start();
t3.Start();

CodePudding user response:

To have all thread starts in a single line, just remove the line breaks after t1.Start(); and t2.Start(); (just kidding).

I assume, you want to start all threads at the same time (down to a nanosecond). That's not possible - as it is not possible to assign multiple variables at the same time. The line where you assign the threads names (via a Tuple) is just a c# syntactic sugar. It results in multiple statements as can be seen e.g. on Sharp Lab (I've linked a sample).

CodePudding user response:

You can't call the Start() method of multiple objects in one statement as you would assign the same value to multiple variables in one statement: The Start() method is an element within each object, not the same piece of code attached to each one. The closest you're going to be able to come is in IamK's comment

(new List<Thread> { t1, t2, t3 }).ForEach(_=> _.Start());

which is a valid construct, as opposed to the merely conceptual one I thought up

(t1, t2, t3).Start();
  • Related