Skip to content

ParametrizedThreadStart Example

April 14, 2009
tags: ,

A simple example of using the ParametrizedThreadStart delegate in C# consists of three steps:

1.  Add the apropriate namespace declaration and write the function that needs to be run on a different thread:

using System.Threading;
static void Work(Object o)
{
        Console.WriteLine((string)o);
}

2. Declare the delegate:

 ParameterizedThreadStart pts = new ParameterizedThreadStart(Work);

3. Declare the thread and start it:

Thread t = new Thread(pts);
t.Start("Parameter String!");

The output should be “Parameter String!”. Remember  that it is best practice to always check for casting errors.


Of course, you could use the simpler syntax in which you do not even create the delegate, it can be inferred by the compiler. You could write just (instead of step 3):

Thread t = new Thread(Work);

and the code would work the same.


					
Advertisements
No comments yet

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

%d bloggers like this: