How to pass parameters to a thread

Source: Internet
Author: User

Many people know how to start a thread, but do not know how to pass parameters to the thread correctly.

 

A common mistake is to use global variables to pass parameters to the thread. In fact, the disadvantage of this method is that it is not safe, the other is troublesome, and the third is that if multiple threads are to be enabled, it is more troublesome.

 

The correct method is to encapsulate the parameters and thread entry functions required by the thread into a class separately, and encapsulate them if some auxiliary functions are needed. In this way, the code is concise, clear, and easy to reuse.

 

Next, we will use a Thread class example to illustrate it in detail. The first is the Thread class:

// -------------------------- Threadfun class ------------------------------------

//-----------------------------------------------------------------------------

// --- File: clsthreadfun. CS

// --- Description: This class demonstrates how to use Thread class.

// --- Author: Knight

// --- Date: mar.21 and 2006

//-----------------------------------------------------------------------------

// ------------------------ {Threadfun class }----------------------------------

Using system;

 

Namespace csnewtest

{

/// <Summary>

/// Summary description for clsthreadfun.

/// </Summary>

Public class clsthreadfun

{

Private string strusername;

Public String Username

{

Get {return strusername ;}

Set {strusername = value ;}

}

 

Public clsthreadfun (string susername)

{

//

// Todo: Add constructor logic here

//

Strusername = susername;

}

 

/// <Summary>

/// Thread interface function

/// </Summary>

Public void threadfun ()

{

// Detail thread handle

}

}

}

 

Next, call the code:

Clsthreadfun mythreadfun = new clsthreadfun ("test ");

// Set parameter through "mythreadfun. Username"

Thread mythread = new thread (New threadstart (mythreadfun. threadfun ));

Mythread. Start ();

 

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.