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.
DetailsCodeAs follows (this example is from msdn)
Using System;
Using System. Threading;
// the threadwithstate class contains the task to be executed and the method for executing the task
Public class threadwithstate {
// the attribute to be used, that is, the parameter to be passed
private string boilerplate;
private int value;
// constructor with parameters
Public threadwithstate ( string text, int Number)
{< br> boilerplate = text;
value = Number;
}
//The method to be thrown to the thread for execution. This method has no return type to allow threadstart to call.
Public VoidThreadproc ()
{
//Here is the task to be executed. Only the input parameters are displayed here.
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.
Threadwithstate TWS = New Threadwithstate (
" This report displays the number {0 }. " , 42 );
// Create the thread for executing the task and execute
Thread t = New Thread ( New Threadstart (TWS. threadproc ));
T. Start ();
Console. writeline ( " Main thread does some work, then waits. " );
T. Join ();
Console. writeline (
" Independent task has completed; main thread ends. " );
}
}