[C#] Multithreading in C# 3 [2] – Thread with Parameters

It is quite easy to create a new thread using the “Thread” class and the “ThreadStart” delegate. The problem of the “ThreadStart” delegate is that we cannot pass any data into it. To solve this problem, the “ParameterizedThreadStart” delegate is introduced.

1. ThreadStart Delegate

The “ThreadStart” delegate is pretty simple. No parameters and no return value.

Thread printPlus = new Thread(() =>
  {
    for (int i = 1; i <= 100; i++)
    {
      Console.Write(i);
    }
  });
  printPlus.Start();

2. ParameterizedThreadStart Delegate

The “ParameterizedThreadStart” delegate accepts a parameter as an object and returns nothing.

public delegate void ParameterizedThreadStart(Object obj);

When you use the “ParameterizedThreadStart” delegate, you need to use the “Thread.Start(object)” method to pass the parameter object.

public sealed class Thread
{
  public void Start(Object parameter);
}

3. Using ParameterizedThreadStart

Let’s modify the first example. Rather than printing 1 to 100, let’s pass the start number and the ending number.

At first, you need a parameter object.

public class RangeParameter
{
  public int Start { get; set; }
  public int End { get; set; }
}

Next, You need a method for a delegate.

public static class PrintNumbers
{
  public static void Print(object parameter)
  {
    RangeParameter data = parameter as RangeParameter;
    for (int i = data.Start; i < data.End; i++)
      Console.Write(i + " ");
  }
}

Finally, you need to create a thread and start it.

public static void Test1()
{
  RangeParameter data = new RangeParameter { Start = 10, End = 120 };
  Thread printTask = new Thread(new ParameterizedThreadStart(PrintNumbers.Print));
  printTask.Start(data);

  // Main task
  for (int j = 0; j < 100; j++)
    Console.Write("- ");

  printTask.Join();
}

4. Using ParameterizedThreadStart with Lambda Expression

In the previous section, I created a static method to demonstrate how the delegate works.

In the real code, you might change the code like this:

public static void Test1()
{
  RangeParameter data = new RangeParameter { Start = 10, End = 120 };
  Thread printTask = new Thread(parameter =>
    {
      RangeParameter param = parameter as RangeParameter;
      for (int i = param.Start; i < param.End; i++)
        Console.Write(i + " ");
    });

  printTask.Start(data);

  // Main task
  for (int j = 0; j < 100; j++)
    Console.Write("- ");

  printTask.Join();
}

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s