C#多線程開發3:給線程傳遞資料的兩種方法,

來源:互聯網
上載者:User

C#多線程開發3:給線程傳遞資料的兩種方法,

定義需要傳遞給線程的資料。

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類對象時,通過建構函式傳入線程需要的資料。


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.