How to use a method with a parameter in a ThreadStart Call without ParameterizedThreadStart

01 Apr

So I am working on a Multi-Thread windows service and when I start the service I need to pass a string parameter but I ran into a issue, ParameterizedThreadStart does not allow multiple parameter passing and you get no compile-time checking without having to cast from object all the time.
So whats the solution? Lambda expressions my friend Lambda expressions.
So here is how you do it and the benefits are that you can pass multiple parameters and you get compile time checking out of the box.

string clientName = "MyClient"
Thread myThread = new Thread(() => getClientFilesAndImport(ClientName));

in C# 2.0 you would use this as I have been told it does not work outside of 4.5 by a few people

string clientName = "MyClient"
Thread myThread = new Thread(delegate() { getClientFilesAndImport(ClientName); })

and there you go full implementation of parametrized methods in threads you spin off šŸ™‚ without all the pitfalls.

Leave a comment

Posted by on April 1, 2013 in C#


Tags: , , ,

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: