定義需要傳遞給線程的數據。
class Student { public string Name { get; set; } public int Age { get; set; } public int Score { get; set; } } List方法1:使用ParameterizedThreadStart委托來傳遞數據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} };
static void Main(string[] args) { Thread t = new Thread(new ParameterizedThreadStart(MethodWithParameters)); t.Start(studentList); } static void MethodWithParameters(object o) { List使用ParameterizedThreadStart委托時,線程方法必須滿足條件:有一個object類型的參數,且返回類型為void。studentList = (List )o; foreach (Student s in studentList) { Console.WriteLine(s.Name + "," + s.Age + "," + s.Score); } }
可以利用這個object類型的參數傳遞數據給線程。
方法2:將線程執行的方法與線程需要的數據封裝進同一個類
class ThreadModel { private ListstudentList; 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(); }
在創建ThreadModel類對象時,通過構造函數傳入線程需要的數據。