Network applications generally use threads more or less. It can be said that a network application with a slightly powerful function always opens more or less threads in it, if the number of threads opened in an application is greater than two, this program can be called a multi-threaded application. So why are network applications always tied with threads? This is because network applications encounter many unexpected problems during execution. The most common problems are network congestion and waiting.
It usually takes a lot of time for a program to handle these problems. If no thread is used, the program will show slow execution speed and long execution time, errors and slow responses may occur. However, if you put these processes that may cause a large amount of execution time in the thread for processing, it will often be able to greatly improve the running efficiency and performance of the application and achieve better scalability. Does this mean that threads should be widely used in network applications? This is not the case. The thread is actually a double-edged sword. If it is forcibly used wherever it is not needed, it may produce a lot of program garbage, or after the program ends, application suspension and other problems due to the failure to destroy the created process.
So if you think your code is fast enough, I suggest you not to use threads or multithreading. I would like to remind you that if you are not very clear about the thread in windows and its execution principles and mechanisms, you can refer to the books on Windows operating systems first, they are generally described in more detail. Then read this article.
1. Introduction to creating and using threads in Visual C:
The threads used in Visual C # are often instantiated through the Thread class in the Self-namespace system. threading. Use the constructor of the thread class to create a thread that can be used by Visual C #. Use the methods and attributes in the thread to set the thread attributes and control the thread status. The most typical constructor syntax in the following Thread class. in Visual C #, this constructor is generally used to create and initialize thread instances.
Public thread (
Threadstart start
);
Parameters
The START threadstart delegate that references the method to be called when the thread starts execution.
Thread also provides other constructor to create a thread, which will not be described here. Table 01 is a common method in the Thread class and its brief description:
Method |
Description |
Abort |
Calling this method usually terminates the thread, but it may cause a threadabortexception type exception. |
Interrupt |
Interrupt a thread in the waitsleepjoin thread state. |
Join |
The call thread is blocked until the end of a thread. |
Resetabort |
Cancels the Abor method called by the current thread. |
Resume |
Continue the suspended thread. |
Sleep |
The number of milliseconds specified by the current thread blocking. |
Start |
The operating system changes the status of the current instance to threadstate. Running. |
Suspend |
The thread is suspended, or it does not work if the thread has been suspended. |
Table 01: common methods and descriptions of thread classes
Note that a thread is executed in. net. After the thread is executed, it will be destroyed automatically. If the thread is not automatically destroyed, you can use the abort method in the thread to manually destroy it. However, note that if the resources used in the thread are not completely destroyed, after the abort method is executed, the thread cannot be destroyed. Some attributes are provided in the Thread class to set and obtain the attributes of the created thread instance. Table 02 contains some common attributes of the thread class and their descriptions:
Attribute |
Description |
Currentculture |
Gets or sets the culture of the current thread. |
Currentthread |
Obtain the currently running thread. |
Isalive |
Gets a value indicating the execution status of the current thread. |
Isbackground |
Gets or sets a value indicating whether a thread is a background thread. |
Name |
Gets or sets the thread name. |
Priority |
Gets or sets a value that indicates the scheduling priority of the thread. |
Threadstate |
Gets a value that contains the status of the current thread. |
Table 02: common attributes of the thread class and their descriptions
Ii. Main content of this article and program debugging and running environment:
The main content of this article is to introduce the high performance that multithreading brings to the compilation of network applications using Visual C. The specific method is to use two different methods in Visual C #. One method adopts multithreading and the other is not to implement the same network application example, the function of this example is to obtain the online status and name of the computer corresponding to multiple IP addresses in the same network segment, by comparing the different execution efficiency of the two methods, we can see how important multithreading is to improve the execution efficiency of network applications. The following are the basic environment configurations for program debugging and running in this article:
(1). Microsoft Windows 2000 Server Edition.
(2) Visual Studio. NET 2002 official version,. NET Framework SDK version 3705.
Iii. Principles of scanning network computers:
The function of this example is to scan IP addresses in a given range to determine whether the computers corresponding to these IP addresses are online. If they are online, the computer name corresponding to the IP address is obtained. The program determines whether the computer is online. It uses DNS resolution for the computer with the given IP address. If the computer name can be parsed Based on the IP address, it indicates that the computer corresponding to the IP address is online. Otherwise, if the IP address cannot be parsed, an exception occurs. By capturing the exception, the computer corresponding to the IP address is not online.
To better illustrate the problem and facilitate the compilation of multi-threaded network applications in Visual C #, This article first introduces the compilation steps of network computer scanning programs that are not based on multithreading, then, modify the program to a multi-threaded computer scanning program, and compare the execution efficiency of the two programs. Then, you will find that the thread plays an important role in network programming.
Iv. Visual C # non-multithreading-based network computer scanning program
In Visual C #, follow these steps to implement a network computer scanner that is not based on multithreading:
1. Start Visual Studio. NET and create a new Visual C # project named scan network computer ].
2. set Visual Studio. switch the current window of net to the form1.cs window, drag the following components to form1 form from the Windows Forms components tab in the toolbox, and perform the corresponding operations:
The four numericupdown components are used to combine them into an IP address range.
A ListBox component used to display scan results.
A progressbar component used to display the program running progress.
Four label components are used to display prompt information.
A groupbox component.
A button component named button1. After the component is dragged into the form, double-click button1, so that Visual Studio. NET will generate the processing code corresponding to the Click Event of the button1 component.
The interface settings are as follows:
Figure 01: design page of the scan Network Computer Project
3. Switch the current window of Visual Studio. NET to form1.cs To Go To The form1.cs file editing interface. In the form1.cs header, replace the default imported namespace code with the following code:
Using system; Using system. drawing; Using system. collections; Using system. componentmodel; Using system. Windows. forms; Using system. Data; Using system. net. Sockets; Using system. net; |
4. Use the following code to replace the processing code corresponding to the click Time of button1 in form1.cs. The function of the following code is to scan a given IP address range and display the scan result.
Private void button#click (Object sender, system. eventargs E) { Listbox1.items. Clear (); // Clear the scan result display area Datetime starttime = datetime. now; // Obtain the current time String mask = numericupdown1.value. tostring () + "." + numericupdown2.value. tostring () + "." + Numericupdown3.value. tostring () + "."; Int min = (INT) numericupdown4.value; Int max = (INT) numericupdown5.value; If (min> MAX) { MessageBox. Show ("The Entered IP address range is invalid. Please check it! "," Error! "); Return; } // Determine whether the Entered IP address range is valid Progressbar1.minimum = min; Progressbar1.maximum = max; Int I; For (I = min; I <= max; I ++) { String IP = mask + I. tostring (); IPaddress myip = IPaddress. parse (IP ); // IPaddress instance based on the given IP address string Try { Iphostentry myhost = DNS. gethostbyaddress (myip ); String hostname = myhost. hostname. tostring (); Listbox1.items. Add (IP + "name:" + hostname ); } Catch { Listbox1.items. Add (IP + "no response from the host! "); } Progressbar1.value = I; } // Scan whether the computer corresponding to the specified IP address is online Datetime endtime = datetime. now; Timespan Ts = endtime-starttime; // Obtain the time used to scan the network computer Label4.text = ts. Seconds. tostring () + "seconds "; MessageBox. Show ("detection completed successfully! "," Prompt "); Progressbar1.value = min; } |
Because the above Code is relatively simple and the comments in the Code are also more detailed, I will not explain it here, but please note the processing method of the time and date data in the code above. This is because many people have asked me a similar question.
5. so far, all the work of the multi-thread-based [scan network computer] project has been completed, and the program execution is very mechanical. The method is to perform DNS resolution on each IP address in order, the resolution result is obtained, so the program execution time is proportional to the size of the IP address range for scanning. Figure 02 is the running interface after the program runs, scanning "10.138.198.1" to "10.138.198.10" for the IP address range computer. The running time of the entire program is 43 seconds:
Figure 02: running interface of a multi-thread-based [scan network computer] project
5. Modify the [scan network computer] program into a program based on multiple threads:
Before changing to a multi-threaded program, you must face and solve the following problems:
1. The thread has no return value. Therefore, processing and calling in the thread should be a process. Therefore, the computer code corresponding to the IP address scanned should be packaged into a process.
2. The process of processing in the thread, because there is no return value, it is impossible to pass a value to the main program (process. However, the process of scanning the computer corresponding to the IP address must pass the data of the IP address online to the main program (process). Therefore, before changing the IP address to a multi-threaded program) data transmission problems.
The following describes how to modify a network computer project to a multi-threaded program:
1. Because threads are used in the program, add the following code to the code area of the imported namespace in the form1.cs code header. The following code is the namespace Where the imported Thread class is located.
2. Add the following statement to the namespace code area of form1.cs code. The following statement defines a delegate:
Public Delegate void updatelist (string sip, string shostname ); |
3. Add the following code to the class code area definition of form1 in form1.cs. The following Code defines a variable to store the execution time of the program:
Private system. datetime starttime; |
4. add the following code after the main function of form1.cs code. The following Code creates a class named Ping. This class can receive the given IP address string through its set attributes, then, it determines whether the computer corresponding to the IP address string is online and receives data transmitted from the thread through its hostname attribute.
Public class ping { Public updatelist ul; Public String IP; // Define a variable to receive the sent IP address string Public String hostname; // Define a variable to pass online data of the corresponding IP address to the master progress Public void scan () { IPaddress myip = IPaddress. parse (IP ); Try { Iphostentry myhost = DNS. gethostbyaddress (myip ); Hostname = myhost. hostname. tostring (); } Catch { Hostname = ""; } If (hostname = "") Hostname = "no response from the host! "; If (UL! = NULL) Ul (IP, hostname ); } // Define a process (as can be seen as a method) to determine whether the computer corresponding to the sent IP address is online } |
5. After adding the above Code to form1.cs, add the following code:
Void updatemylist (string sip, string shostname) { Lock (listbox1) { Listbox1.items. Add (SIP + "" + shostname ); If (progressbar1.value! = Progressbar1.maximum) { Progressbar1.value ++; } If (progressbar1.value = progressbar1.maximum) { MessageBox. Show ("detection completed successfully! "," Prompt "); Datetime endtime = datetime. now; Timespan Ts = endtime-starttime; Label4.text = ts. Seconds. tostring () + "seconds "; // Display the time required to scan the computer Progressbar1.value = progressbar1.minimum; } } } |
6. Use the following code to replace the processing code corresponding to the button1 Click Event in form1.cs. The following code function is to create multiple computer thread instances that scan for a given IP address range and display scan results.
Private void button#click (Object sender, system. eventargs E) { Listbox1.items. Clear (); // Clear the scan result display area Starttime = datetime. now; // Obtain the current time String mask = numericupdown1.value. tostring () + "." + numericupdown2.value. tostring () + "." + Numericupdown3.value. tostring () + "."; Int min = (INT) numericupdown4.value; Int max = (INT) numericupdown5.value; If (min> MAX) { MessageBox. Show ("The Entered IP address range is invalid. Please check it! "," Error! "); Return; } // Determine whether the Entered IP address range is valid Int _ threadnum = max-min + 1; Thread [] mythread = new thread [_ threadnum]; // Create one or more thread instances Progressbar1.minimum = min; Progressbar1.maximum = MAX + 1; Progressbar1.value = min; Int I; For (I = min; I <= max; I ++) { Int K = max-I; Ping hostping = new Ping (); // Create a ping instance Hostping. IP = mask + I. tostring (); Hostping. UL = new updatelist (updatemylist ); // Send an IP address string to the ping instance Mythread [k] = new thread (New threadstart (hostping. Scan )); // Initialize a thread instance Mythread [K]. Start (); // Start the thread } } |
So far, the [scan network computer] project has been modified into a multi-threaded program. At this time, the program is running and the computer corresponding to the given IP address range is also scanned, you will be surprised to find that the program execution time is set to 10 seconds. No matter how many computers you want to scan, the program runs for about 10 seconds, this is because the program assigns a thread to scan each IP address, so that the program execution time is not associated with the number of IP addresses in the IP address segment to be scanned, in this way, the running time of the program is greatly reduced, and the running efficiency of the program is improved. This fully reflects the benefits of multithreading for network programming. Figure 03 run the computer on the IP address range 10.138.198.1 to 10.138.198.10 as shown in the following figure:
Figure 03: operation interface of the multi-thread "scan network computer" Project
By comparing the two programs, the correct use of threads in the preparation of network applications can greatly improve the program running efficiency.
Vi. Summary:
So far, all the content to be introduced in this section is over. I wonder if you have understood and mastered the following points through the above introduction:
1. How to get the current system time and add or subtract time and date data.
2. What are the reasons for using threads (multithreading) when writing network applications and the advantages of threads (multithreading) for network applications.
3. How to create multiple thread instances in the application.
4. How to implement a thread with "return value.
If you can master all the above points, it would be better. However, if you are still confused about the thread and its usage, it doesn't matter. After all, the thread is rich in programming technology and uses complicated stuff, it is really difficult to grasp it right away. This article will be introduced later.