Monday, October 31, 2011

How to pass data as an argument to Thread?


In this post I will explain how to pass parameters to thread’s method. There are multiple ways to achieve this. Let’s have a look on below easiest way to pass arguments to thread’s method.

public static void main()
{
    Thread t = new Thread(DisplayMessage);
    t.Start("Mitesh");
}
public void DisplayMessage(object msg)
{
    Console.WriteLine("Hello " + msg.ToString());
}

Output
Hello Mitesh

In above example, DisplayMessage method takes one argument as an object and display passed arguments. The new thread initialization has reference of DisplayMessage and Thread constructor takes two types of argument one is ThreadStart and another is ParameterizedThreadStart. So this method will treat as ParameterizedThreadStart. The ParameterizedThreadStart will take only one argument and that argument should be passed as an object. The Start method of Thread takes one argument as an object so we can pass only one argument to start method of Thread.

Let’s have a look on another way to pass data as an argument to Thread.

public static void main()
{
    Thread t = new Thread(() => DisplayMessage("Mitesh"));
    t.Start();
}
public void DisplayMessage(object msg)
{
    Console.WriteLine("Hello " + msg.ToString());
}

Or

public static void main()
{
    Thread t = new Thread(delegate() { DisplayMessage("Mitesh"); });
    t.Start();
}
public void DisplayMessage(object msg)
{
    Console.WriteLine("Hello " + msg.ToString());
}
Output
Hello Mitesh

We can also pass arguments using Lambda expression or using anonymous method as shown in above examples.

Hope you liked this tip. Please leave your feedback and comments in comment section below in this post.

See also –


No comments:

Post a Comment