LP on .NET

July 2, 2009

System.Threading.Thread Constructors Tip

Filed under: .NET,C#,Software Development,Visual Studio — Larry Parker @ 11:48 am

Just a quick tip when calling any of the constructors for System.Threading.Thread.  Many examples (including the MSDN documentation) explicitly create a ThreadStart (or ParameterizedThreadStart) instance and pass that into the constructor:

void DoIt()
{
    Thread thread = new Thread(new ThreadStart(DoWork));
    thread.Start();
}

void DoWork()
{
}

This is of course totally fine, but you can save a couple of keystrokes by just passing in the method name itself:

void DoIt()
{
    Thread thread = new Thread(DoWork);
    thread.Start();
}

This compiles to the exact same IL code (you can see this for yourself using Reflector or some other utility).

I just find it a bit easier than instantiating an object, and the code is easier to read as well.

Hope this helps!

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: