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);
}
Nice explanation regarding this topic.Good.Keep sharing.Please update all information.Thank u.
ReplyDelete