C # multi-thread development 3: Two Methods for passing data to a thread

Source: Internet
Author: User

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.

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.