WebHosting

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

How to Enable and Configure Remote Desktop (RDP) on Ubuntu 24.04.4 LTS

Remote Desktop Protocol (RDP) support in Ubuntu has become considerably easier with the GNOME Remote Desktop stack included in modern Ubuntu...