C # solution for changing multithreading to passing Parameters

Source: Internet
Author: User

 

When writing a multi-threaded program, parameters cannot be passed in the delegate call method, but I encountered a problem. The thread delegate method must pass parameters because I have multiple threads, the method bodies registered by multiple threads are basically the same. There are only a few variables with different values. I do not want to write method 1 (){......} ; Method 2 (){......} Method 3 (){......} Wait, because my thread may be 100 or more, so I gave up this method, wanted to use a method, then threw a parameter into it, and handled it in a loop, in this way, we can demonstrate the simplicity of the program and the style of excellent programmers.,

So I checked some information online and communicated with my colleagues to come up with a solution:
First ~ A variable is defined in the class called by the thread, and a variable is also defined in the method entrusted by the thread. Of course, this variable is what you want to wear, then the first sentence in the method body is "method body variable = Class variable"; start these threads with a loop, and these threads also register this method body.
Key code:
For (int I = 0; I <_ MAXSERVER; I ++)
{
Class variable = (ServerBean) serverState [I]; // class variable value assignment
Thread th = new Thread (new ThreadStart (ScanPort); // ScanPort is one of my method bodies.
Th. Start ();
Thread. Sleep (10); // sleeping for 10 seconds here is the first sentence to give the started thread enough time to execute it.
Assignment Statement
}

Okay. The general idea is like this ~~ If you have any questions or encounter the same problems, you can discuss them.
In addition, I am still studying the problem that a task is completed by multiple threads synchronously. It seems that I want to use the threadpool thread pool for management. After the study, I will continue to publish it ~

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.