In. NET Framework 2.0, there are two ways to implement a thread call method with parameters.
First, use ParameterizedThreadStart.
When the System. Threading. Thread. Start (System. Object) overload method is called, the objects containing data are passed to the Thread.
Using ParameterizedThreadStart is not a safe method for passing data types, because the System. Threading. Thread. Start (System. Object) method overload accepts any Object.
This method is not recommended, so it is not detailed here, the specific usage see: http://msdn2.microsoft.com/zh-cn/library/system.threading.parameterizedthreadstart (VS.80). aspx
ParameterizedThreadStart ParStart = new ParameterizedThreadStart (ThreadMethod );
Thread myThread = new Thread (ParStart );
Object o = "hello ";
MyThread. Start (o );
// ThreadMethod:
Public void ThreadMethod (object ParObject)
{
// Program code
}
Second, encapsulate the methods and parameters of thread execution into a class. By instantiating this class, the method can call attributes to implement indirect type-safe parameter passing.
The Code is as follows (this example is from MSDN)
Using System;
Using System. Threading;
// The ThreadWithState class contains the task to be executed and the method to execute the task.
Public class ThreadWithState {
// The attribute to be used, that is, the parameter to be passed
Private string boilerplate;
Private int value;
// Constructor Containing Parameters
Public ThreadWithState (string text, int number)
{
Boilerplate = text;
Value = number;
}
// Method to be thrown to the thread for execution. There is no return type in this place to allow ThreadStart to call
Public void ThreadProc ()
{
// Here is the task to be executed. Only the input parameters are displayed.
Console. WriteLine (boilerplate, value );
}
}
// The class used to call the above method is the entry for execution in this example.
Public class Example {
Public static void Main ()
{
// Instantiate the ThreadWithState class to provide parameters for the thread