When writing multithreaded procedures, it is often the method that the delegate calls cannot pass parameters, but I encountered a problem, the thread delegate method must pass parameters, because I have more than one thread, and more than one thread registered method body is basically the same, only a few variable values, I do not want to write what Method 1 () {... ...} ; Method 2 () {...} Method 3 () {...} Wait, because my thread might be 100, or more, so I give up this method, want to use a method, and then throw parameters to the inside, to use the loop to fix it, so as to show the simplification of the program, and excellent programmer style, so I went online to look up some information, and with colleagues to exchange, Come up with a solution:
First, the thread-called class defines a variable, and then the thread-delegate method also defines a variable, which, of course, is what you want to wear, and then the first word in the method body is "the variable of the method body = Class"; Use a loop to start the threads, and the threads are also registering the method body
Key Code section:
for (int i = 0; i < _MAXSERVER; i++)
{
类变量= (ServerBean)serverState[i];//类变量赋值
Thread th = new Thread(new ThreadStart(ScanPort));//ScanPort是我的一个方法体
th.Start();
Thread.Sleep(10);//这里睡上10秒是为了让启动的这个线程有足够的时间去执行它的第一句
赋值语句
}
Well, the general idea is this ~ ~ There is not understand or encounter the same problem can discuss the discussion