Application of multithreading in Visual C # network programming

Source: Internet
Author: User
Tags define execution header terminates thread thread class tostring valid
visual| Programming | multithreading | network

Network applications are more or less used to threading, or even a slightly more powerful network application will always be in a more or less thread, if the application in the number of threads out of more than two, then you can call this program multithreaded applications. So why are web apps always intertwined with threads? This is because the network application in the implementation of the time, will encounter many unexpected problems, the most common is network congestion and network waiting.

Procedures in dealing with these problems often take a lot of time, if not using a thread, the program will be executed in the performance of such as slow, long execution time, error prone, unresponsive and so on. And if these processes that can cause a large amount of program execution time to be handled in a thread, they tend to greatly improve the operational efficiency and performance of the application and achieve better scalability. So does this mean that threads should be used extensively in Web applications? This is not the case, the thread is actually a double-edged sword, if not the occasion, where no need to use the use of force may generate a lot of program garbage, or at the end of the program, because there is no ability to destroy the process created to cause the application hangs and so on.

So if you think you're writing code fast enough, I'm going to give you the advice of not using threads or multithreading. Here's a reminder that if you're not quite sure about the threads and the principles and mechanisms behind windows, you can refer to the books on Windows operating systems, which are generally described in more detail. Then read this article again.

I. Introduction creating and Using Threads in Visual C #:

The threads used in Visual C # are all often instantiated through the thread class in the System.Threading of the namespace. The thread class's constructor is used to create threads that are available to Visual C #, setting the thread properties and controlling the state of the thread through the methods and properties in thread. The most typical constructor syntax in the following thread class is typically used in Visual C # to create and initialize the thread instance.

Public Thread (
ThreadStart start
) ;

Parameters

The start ThreadStart delegate, which references the method to invoke when this thread starts execution.

Thread also provides additional constructors to create threads, which are not covered here. Table 01 is some of the commonly used methods in the thread class and their brief descriptions:


Method Description
Abort Calling this method usually terminates the thread, but it can cause a ThreadAbortException type exception.
Interrupt Interrupts a thread that is in the WaitSleepJoin thread state.
Join Blocks the calling thread until a thread terminates.
ResetAbort Cancels the Abor method invoked by the current thread.
Resume Continue the suspended thread.
Sleep The current thread is blocking the specified number of milliseconds.
Start The operating system changes the state of the current instance to threadstate.running.
Suspend Suspends the thread, or it does not work if the thread is suspended.
Common methods of table 01:thread classes and their descriptions

Here's what you should be aware of. NET executes a thread, which is usually automatically destroyed when the thread finishes execution. If the thread is not automatically destroyed, it can be manually destroyed by the Abort method in thread, but also note that if the resource used in the thread is not completely destroyed, the Abort method does not guarantee that the thread will be destroyed after it is executed. Some properties are also provided in the thread class to set and get the thread instance properties created, and some common properties of the thread class and their descriptions are described in table 02:

description
currentculture
currentthread
isalive
isbackground
name
priority
threadstate
Common Properties of Table 02:thread classes and their descriptions
  two. The main content of this article and program debugging and operating environment:

The main content of this article is to introduce the more high-performance improvements that multithreading brings to writing network applications in Visual C #. The specific approach is to use two different methods in Visual C #, one with multiple threads and the other not to implement the same example of a specific network application, which is the function of obtaining the online status and the corresponding computer name of the computer that corresponds to multiple IP addresses on the same network segment of the network. By comparing the different execution efficiencies of these two methods, we can know how important multithreading is to improve the execution efficiency of the network application. The following are the basic environment configurations designed to debug and run programs in this article:

(1). Microsoft Windows 2000 Server Edition.

(2). Visual Studio. NET 2002 Official edition,. NET FrameWork SDK version number 3705.

   three. The principle of scanning network computer

The function of the example below is to determine whether the computer is online by scanning a given interval IP address, and to obtain the computer name that corresponds to the IP address if online. Program to determine whether the computer online is the use of a given IP address of the computer DNS resolution, if the corresponding IP address to resolve the computer name, then this IP address corresponding to the computer online; Conversely, if the resolution does not come out, it will produce an abnormal error, through the capture of the exception, The computer to which this IP address corresponds is not online.

To better illustrate the problem and make it easier to learn how to write multithreaded network applications in Visual C #, this article first introduced is not based on multithreading network computer scanning program to write steps, and then on its basis, to modify it into a multithreaded computer scanning program, and finally compare the execution efficiency of these two programs, You will find that threads play an important role in network programming.
  Four. Visual C # Implementation of a network computer scanner that is not based on multithreading

The following are steps for implementing a network computer scanner that is not multithreaded in Visual C #:

1. Start visual Studio. Net and create a new Visual C # project with the project name "Scan network computer."

2. Take visual Studio. NET to the Form1.cs window, and from the Windows Forms Components tab in the Toolbox, drag the following components into the Form1 form and perform the appropriate actions:

Four NumericUpDown components that combine to form an IP address range.

A ListBox component that displays the results of the scan.

A ProgressBar component that displays the progress of a program.

Four label components to display the hint information.

A GroupBox component.

A button component, named Button1, and after this component is dragged into the form, double-click Button1 to Visual Studio. NET produces the processing code corresponding to this button1 component click event.

The interface is set as shown below:


Figure 01: The Design interface for the "Scan network computer" project

3. Take visual Studio. NET's current window switches to "Form1.cs" and enters the editing interface of the Form1.cs file. In the Form1.cs header, replace the system default import 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. Replace the button1 in Form1.cs with the following code, the function of the following code is to scan a given IP address range and display the scan results.

private void Button1_Click (object sender, System.EventArgs e)
{
ListBox1.Items.Clear ();
Clear scan results show area
DateTime starttime = DateTime.Now;
Get 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 IP address range entered is not valid, please check!") "," the mistake! " ) ;
return;
}
Determine if the IP address range entered is legitimate
Progressbar1.minimum = Min;
Progressbar1.maximum = Max;
int i;
for (i = Min; I <= Max; i++)
{
String ip= Mask + i.tostring ();
IPAddress MyIP = Ipaddress.parse (IP);
The situation 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 is:" + HostName);
}
Catch
{
LISTBOX1.ITEMS.ADD (IP + "host does not respond!");
}
progressBar1.Value = i;
}
Scan the computer for a given IP address is online
DateTime endtime = DateTime.Now;
TimeSpan ts = endtime-starttime;
Get the time used to scan a network computer
Label4. Text = ts. Seconds.tostring () + "seconds";
MessageBox.Show ("Successfully completed detection!") "," hint ");
progressBar1.Value = Min;
}

Since the above code is simpler, and the comments in the code are more detailed, this is not explained here, but notice how the data for the date type is handled in the code above. Because a lot of people have questioned me about similar problems.

5. At this point, all work on the "Scan network computer" project, which is not based on multithreading, is complete, the implementation of the program is very mechanical, the method is to each IP in order DNS resolution, and the results are resolved, so the program's execution time and scan the IP address interval segment size is proportional. Figure 02 is the running interface after the program is run to scan the IP address interval computer "10.138.198.1" to "10.138.198.10". The entire program runs for 43 seconds:


Figure 02: The Running interface of the "Scan network computer" project without multithreading
  Five. Modify the "Scan network computer" program to a multithreaded program

Before you modify a multithreaded routine, you must confront and resolve the following issues:

1. A thread is not a return value, so it is a process that is processed and invoked in threads, so the code for the computer that scans the IP address is packaged into a process.

2. Put the process in the thread, because there is no return value, so you cannot pass the value to the main program (process). However, the process of scanning the computer that corresponds to the IP address is to pass data to the main program (process) whether the IP address is online, so you must pass the data from the thread to the main program (process) before you modify it into multithreaded programs.

This is based on the "Scan network computer" project and modifies it to a specific implementation step based on a multithreaded program:

1. Due to the use of the thread in the program, the following code is added to the Form1.cs code header, and the following code is the namespace in which the thread class is imported.

Using System.Threading;

2. Add the following statement to the namespace code area of the Form1.cs code, and the following statement defines a delegate:

public delegate void Updatelist (String SIP, string shostname);

3. The Class Code area definition of Form1 in Form1.cs adds the following code, which defines a variable that holds the time the program executes:

Private System.DateTime StartTime;

4. After Form1.cs the main function of the code, add the following code, which is to create a class called Ping, which can receive the given IP address string through its set properties, and then determine whether the IP address string corresponds to the computer online and through its set of hostname property to receive data that is passed from the thread.

public class Ping
{
Public Updatelist ul;
public string IP;
Define a variable to receive the transmitted IP address string
public string HostName;
Define a variable to pass the corresponding IP address to the master to see if the data is online
public void Scan ()
{
IPAddress MyIP = Ipaddress.parse (IP);
Try
{
Iphostentry myHost = dns.gethostbyaddress (MyIP);
HostName = MyHost.HostName.ToString ();
}
Catch
{
HostName = "";
}
if (HostName = "")
HostName = "Host is not responding!" ";
IF (UL!= null)
UL (IP, HostName);
}
Define a process (also can be seen as a method) to determine whether the transmitted IP address corresponds to the computer online
}

5. After adding the above code in 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 ("Successfully completed detection!") "," hint ");
DateTime endtime = DateTime.Now;
TimeSpan ts = endtime-starttime;
Label4. Text = ts. Seconds.tostring () + "seconds";
Show the time required to scan your computer
progressBar1.Value = Progressbar1.minimum;
}
}
}

6. Replace the processing code for the Button1 click event in Form1.cs with the following code, which is to create multiple instances of the computer thread that scan the given IP address interval and display the results of the scan.

private void Button1_Click (object sender, System.EventArgs e)
{
ListBox1.Items.Clear ();
Clear scan results show area
StartTime = DateTime.Now;
Get 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 IP address range entered is not valid, please check!") "," the mistake! " ) ;
return;
}
Determine if the IP address range entered is legitimate
int _threadnum = max-min + 1;
thread[] Mythread = new Thread [_threadnum];
Create a multiple thread instance
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);
To pass an IP address string to this ping instance
MYTHREAD[K] = new Thread (new ThreadStart (Hostping.scan));
Initializes an instance of a thread
MYTHREAD[K]. Start ();
Start thread
}
}

Thus, "Scan network computer" project has been modified into a multithreaded program, at this time the program is running, and also scan the given IP address interval corresponding to the computer, it will be surprised to find the program execution time is built 10 seconds, and regardless of the number of computers to be scanned, The program runs for about 10 seconds, this is because the program to scan each IP is assigned a thread, so that the program's execution time is not related to the IP address segment to scan the number of IP addresses associated with, so also greatly reduce the running time of the program, improve the efficiency of the program's operation, This also fully reflects the benefits of multithreading to network programming. Figure 03 is also shown in the running interface after the program scans the IP address interval computer "10.138.198.1" to "10.138.198.10":


Figure 03: The Running interface of the "Scan network computer" project based on multithreading

Through the comparison of two programs, in the writing of network applications, the correct use of threading can greatly improve the efficiency of the program.

   Six. Summary

At this point, the content of this section is all over, I do not know whether you understand through the above introduction, master the following points:

1. How to obtain the system current time, and implement time date type data addition and subtraction.

2. The reasons for using threads (multithreading) and the benefits that threads (multithreading) can bring to network applications when writing Web applications.

3. How to create multiple thread instances in your application.

4. How to implement a thread with a "return value".

If you can master all the above points, that would be a good one. But if you're still feeling blurry about the thread and how it's used, it doesn't matter, after all, threading is a rich and complex thing to use in programming, and it's really hard to get a grip on it immediately. This aspect will also be introduced in future articles.



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.