Defines the data that needs to be passed to the thread.
Class Student {public string Name {get; set;} public int Age {get; set;} public int score {get; set;}} list<student> studentlist = new list<student> () { new Student () {name= "Zhangsan", age=20,score=5}, New Student () {name= "Lisi", age=18,score=4}, new Student () {name= "Wangwu", age=19,score=5}};
method 1: Use the parameterizedthreadstart delegate to pass the data
static void Main (string[] args) { thread t = new Thread (new Parameterizedthreadstart (methodwithparameters)); T.start (studentlist);} static void Methodwithparameters (object o) { list<student> studentlist = (list<student>) o; foreach (Student s in studentlist) { Console.WriteLine (s.name + "," + S.age + "," + S.score); }}
UseParameterizedthreadstartwhen delegating, the thread method must satisfy the condition:
has an argument of type Object and the return type is void.
can take advantage of this Object the parameters of the type pass data to the thread.
Method 2 : Encapsulates the thread execution method with the data required by the thread into the same class
Class threadmodel{ private list<student> studentlist; Public ThreadModel (list<student> studentlist) { this.studentlist = studentlist; } public void Threadmethod () { foreach (Student s in studentlist) { Console.WriteLine (s.name + "," + s.age + "," + S.score);}}} static void Main (string[] args) { ThreadModel ThreadModel = new ThreadModel (studentlist); Thread t = new Thread (new ThreadStart (Threadmodel.threadmethod)); T.start (); }
When you create ThreadModel class object, the data that is required by the thread is passed in through the constructor.
C # multithreaded Development 3: Two ways to pass data to a thread