C # multi-thread development 3: Two Methods for passing data to a thread
Define the data to be passed to the thread.
class Student { public string Name { get; set; } public int Age { get; set; } public int Score { get; set; }}List
studentList = new List
() { 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 ParameterizedThreadStart to transmit data
static void Main(string[] args){ Thread t = new Thread(new ParameterizedThreadStart(MethodWithParameters)); t.Start(studentList);}static void MethodWithParameters(object o) { List
studentList = (List
)o; foreach (Student s in studentList) { Console.WriteLine(s.Name + "," + s.Age + "," + s.Score); }}
When ParameterizedThreadStart is used for delegation, the thread method must meet the following conditions:
There is a parameter of the object type and the return type is void.
You can use this object type parameter to pass data to the thread.
Method2: Encapsulate the thread execution method and the data required by the thread into the same class.
class ThreadModel{ private List
studentList; public ThreadModel(List
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 creating a ThreadModel Class Object, pass in the data required by the thread through the constructor.