Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Does ParameterizedThreadStart Only Allow Object Parameter?

Please let me know why ParameterizedThreadStart class only allow method which only System.object argument type contain.

public class MainThreadTest
{
    public static void Main(string[] args)
    {
        Thread T = new Thread(new ParameterizedThreadStart(DisplayYOrX));
        T.Start("X");

        DisplayYOrX("Y");
    }

    static void DisplayYOrX(object outValue)
    {
        string Parameter = (string)outValue;

        for(int i=0; i<10; i++)
            Console.Write(Parameter);
    }
}

Why I would like to know about that is I do not want to use type cast syntax again.

string Parameter = (string)outValue;
like image 302
Frank Myat Thu Avatar asked Jan 21 '12 05:01

Frank Myat Thu


People also ask

Why does a delegate need to be passed as a parameter to the Thread class constructor?

Why is the Constructor of the Thread class Taking a Parameter of Delegate Type? As we already discussed, the main objective of creating a Thread in C# is to execute a function. A delegate is a type-safe function pointer.

Which delegate is required to Start a thread with one Parameter?

The ParameterizedThreadStart delegate supports only a single parameter.

How to pass the data to the thread?

To pass data into the thread we will simply pass it as an input parameter to the method that is being started as a new thread. To get the data from the thread a delegate callback method will be used. First, we will make a regular method that takes in an input parameter.


1 Answers

The reason for the limitation is that ThreadStart isn't a generic delegate and hence it's only capable of passing an object around. This is easy enough to work around though by using a lambda where you directly pass the value.

public static void Main(string[] args) {
  ThreadStart start = () => { 
    DisplayYOrX("X");
  };
  Thread t = new Thread(start);
  t.Start();

  ...
}

static void DisplayYOrX(string outValue) {
  ...
}

Version for C# 2.0

public static void Main(string[] args) {
  ThreadStart start = delegate { 
    DisplayYOrX("X");
  };
  Thread t = new Thread(start);
  t.Start();

  ...
}
like image 78
JaredPar Avatar answered Sep 20 '22 08:09

JaredPar