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