Monday, January 30, 2012

Ways of passing argument to Threads in C#

image

1. The easiest way to pass arguments to a thread’s target method is to execute a lambda expression that calls the method with the desired arguments:


static void Main()
{

//We can pas a string argument like putting () in the thread initialization.
Thread t = new Thread ( () => Print ("Hello from t!") );
t.Start();
}
static void Print (string message)
{
Console.WriteLine (message);
}

With this approach, you can pass in any number of arguments to the method. You can even wrap the entire implementation in a multi-statement lambda:

new Thread (() =>{ Console.WriteLine ("I'm running on another thread!"); Console.WriteLine ("This is so easy!");}).Start();

2. This can also be done with anonymous methods:

new Thread (delegate()
{
//Arguments
}).Start();

 

3. Another technique is to pass an argument into Thread’s Start method:

static void Main()
{
Thread t = new Thread (Print);
t.Start ("Hello from t!");
}
static void Print (object messageObj)
{
string message = (string) messageObj; // We need to cast here
Console.WriteLine (message);
}

1 comment:

  1. Nice explanation regarding this topic.Good.Keep sharing.Please update all information.Thank u.

    ReplyDelete

Thank you for Commenting Will reply soon ......

Featured Posts

Enable shared folders in ubuntu in vmware?

 To enable Shared Folders in Ubuntu (VM) on VMware , follow these steps: Step 1: Enable Shared Folders in VMware Settings Power...