Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# thread declaration

I see the following declarations:

ThreadStart myThreadDelegate = new ThreadStart(Work.DoWork);
Thread myThread = new Thread(myThreadDelegate);
myThread.Start();

Can they be simplified as the following?

Thread myThread = new Thread(new ThreadStart(Work.DoWork));
myThread.Start();

If yes, what is the second method called? what are the pros and cons of each method?

like image 797
CaTx Avatar asked Feb 28 '26 11:02

CaTx


1 Answers

It can even be simplified to:

var myThread = new Thread(Work.DoWork);
myThread.Start();

There's not much of a difference. In your first example, the delegate instance gets a name, myThreadDelegate, that could in theory be used later (maybe for something else) in the method.

It's mostly a matter of taste if one prefers one long expression with many levels in it, or many little expressions with temporaray variables that are then combined.

In any case, it is simpler, in my opinion, to use implicit conversion from method group, as in just Work.DoWork, than to write new ThreadStart(Work.DoWork). See the sentence C# 2.0 provides a simpler way to write the previous declaration in How to: Declare, Instantiate, and Use a Delegate (C# Programming Guide). This simpler way is formally called a method group conversion.

For information on the var keyword, see Implicitly Typed Local Variables (C# Programming Guide).

Of course the ultimate one-liner in your example will be:

(new Thread(Work.DoWork)).Start();

in which case you don't even get a reference to (variable for) your new thread (the instance method Start() returns void).

like image 97
Jeppe Stig Nielsen Avatar answered Mar 02 '26 01:03

Jeppe Stig Nielsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!