question:
For multi-threaded programming, it is often necessary to pass multiple parameters to the thread, while threads in C# only receive 1 object-type parameter (as follows):
Thread t = new Thread(new ParameterizedThreadStart(newthread)); (parameter); void newthread(object) { ............. }
Now you need to pass multiple parameters into the thread. For example, the method method wants to run with a separate thread.
void method(int begin,int end) { .................. }
Solution 1: Create a new class that runs the method
class myclass { private int begin; public int begin { set{=value;} } private int end; public int end { set{=value;} } public run() { method(begin,end); } private method(int begin,int end) { ............... } }
Then create a new instance of this class, and after assignment, you can run away. The code is as follows;
myclass c = new myclass(); =100; =10000; Thread t = new Thread(new Threadstart()) ();
2. Solution 2: Pass the array or collection instance as parameters into
Currently, we are working on a multi-threaded software. When we use this part, we feel that we have to create a new class every time, which is quite troublesome. After checking the mainstream online, we are all in Solution 1. Later, we figured out another method, which is that although the new thread can only pass 1 parameter in, we can pass parameters of a collection or array class in, so that we can solve the problem of passing multiple parameters to the new thread at once.
Similarly, for the above method method, you need to pass 2 int-type integers, first add an overload of the method method.
void method(object o) { //The parameters passed in here are processedint[] p = (int[])o; //Calling the original method methodmethod(p[0],p[1]); }
Then store the parameters to be passed in an array or a collection
int para[]=new int[2]{100,10000};
Finally, create a new thread to call
THread t = new Thread(new ParameterizedThreadStart(method)) (para);
This will achieve the purpose of passing 2 parameters into the thread.
The passed parameter types can also be used with List<> or other sets. The types of these parameters passed in are the same. For different types, you can consider passing them in by List<object> or object[], and then processing the parameters in the overloaded method.
The above is the solution (two) for passing multiple parameters into the thread that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!