C # multithreading becomes a pass-through parameter solution

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.