Overview
The thread function has either no parameters, or only one object parameter, and there is no return value, which greatly reduces the flexibility of the program, but what we want is to be able to use parameters and return values as normal methods! Can this be achieved? Two methods are described below
First, add the Shell method
Principle: Passing parameters into a call to a variable
Method: Defines a specialized thread class.
1. Parameters and return values that need to be passed to the thread as public properties of the class;
2, the real method of the thread function is also put in the class inside
3, the shell of the thread function is also put in the inside (the real call is the method of 2)
Public classmythread{ Public Doublex=Ten; Public Doubley=0;
Public double Result; PublicMyThread (intX,int y) { This. x=X;
This. y= y;
}
True method public double SomeFunc (double x,double y)
{
Addition operations, etc.
}
//Shell-adding method Public voidCalculate () {Result= SomeFunc (x, y);
}}mythread T=NewMyThread () {x=1,y=2}; ThreadStart ThreadStart=NewThreadStart (t.calculate) thread thread=Newthread (threadstart); thread. Start ();
Thread. Join ();
Console.WriteLine (t.Result);
}
Second, design an input and output auxiliary class
Since the thread function of the Parameterizedthreadstart delegate type can enter a parameter of type object, we start with this type of argument: encapsulate the "input parameter" and "return value" of the thread function inside a class, The instance of this class is the only object parameter, and the code is all clear!
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading;namespaceconsoleapplication1{classProgram {Static voidMain (string[] args) {MyThread obj=NewMyThread (); Threadmethodhelper Argu=NewThreadmethodhelper (); argu.x=5; Argu.y=Ten; Thread T=NewThread (obj. SOMEFUNC); T.start (ARGU); T.join (); Console.WriteLine (Argu.returnvalue); Console.read (); } } classThreadmethodhelper {//Method Parameters Public intx; Public inty; //method return value Public Longreturnvalue; } classMyThread { Public voidSomeFunc (ObjectArgu) { Longresult =0; intx = (Argu asthreadmethodhelper). x; inty = (Argu asthreadmethodhelper). Y; Result= x +y; (Argu asThreadmethodhelper). returnvalue =result; } }}
Multi-Threading of C # Secret weapons--parameters and return values