定义需要传递给线程的数据。
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}
};
方法1:使用ParameterizedThreadStart委托来传递数据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);
}
}
使用
ParameterizedThreadStart
委托时,线程方法必须满足条件:
有一个object类型的参数,且返回类型为void。
可以利用这个object类型的参数传递数据给线程。
方法2:将线程执行的方法与线程需要的数据封装进同一个类
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();
}
在创建ThreadModel类对象时,通过构造函数传入线程需要的数据。