C # multithreaded Development 3: Two ways to pass data to a thread

Source: Internet
Author: User

Defines the data that needs to be passed to the thread.

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}};
method 1: Use the parameterizedthreadstart delegate to pass the data

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);     }}
UseParameterizedthreadstartwhen delegating, the thread method must satisfy the condition: has an argument of type Object and the return type is void.

can take advantage of this Object the parameters of the type pass data to the thread.

Method 2 : Encapsulates the thread execution method with the data required by the thread into the same class

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 (); }

When you create ThreadModel class object, the data that is required by the thread is passed in through the constructor.

C # multithreaded Development 3: Two ways to pass data to a thread

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.