The understanding of ASP.net parallelism and multithreading

Source: Internet
Author: User

ASP tutorial. NET Parallelism and multithreading understanding

asp.net tutorial The number of concurrent requests affects a considerable number of times, regardless of program execution time and whether it is blocked, it will be limited by the number of connections, the number of IIS connections, and the limitations of the CLR thread pool.

Server TCP limit, [Hklmsystemcurrentcontrolsetservicestcpipparameters] "enableconnectionratelimiting" =dword:00000000, The value of the registry key changed to "0" can be, if it is such as windows2003 server, generally do not have this limit, such as my own 2003 did not.

IIS connection limit: IIS6 and below,%systemroot%system32inetsrv under the MetaBase.xml file directly modified, such as modify the default asprequestqueuemax= "3000", You can set the request to queue up a larger, modify the default aspprocessorthreadmax= "25", the request concurrent requesting the thread set larger, etc., can refer to the relevant information, the process will be set to the CPU to switch threads to time-consuming, according to the internet, not the bigger the better , but can be synthesized according to the concurrent quantity and the system performance correlation to form the setting; IIS7 configuration is not the same place,%systemroot%system32inetsrvconfigapplicationhost.config file modified, modified < Serverruntime appconcurrentrequestlimit= "5000"/>, concurrent request limit quantity,

IIS Manager > ApplicationPools > Advanced settings, Queue Length : 1000 Modify Queue Length. hklmsystemcurrentcontrolsetserviceshttpparameters maxconnections modified more.

limitations in the. NET Framework

I think a asp.net program does not care about the different versions of IIS, they are not in the same life logic, IIS6 the process is not the same, but I think that the process is at least three thread pools to manage, a CLR responsible for different request requests of the work thread pool, An IO processing thread, as well as an unmanaged level thread pool for the process, the initialization and maximum number of managed two thread pools can be configured and programmed, and unmanaged thread pools are used to relay requests to CLR processing, and unmanaged-level threads that are processed when IO or other asynchronous operations are in place. Of course, the managed-level thread pool we can do some control, different. NET version, and the number of system CPUs, the number of initialization thread pool is not the same, such as my current CPU is a single CPU dual-core system, in the. Net4 the next MVC request executes the following code:

int workthread = 0;
int iothread = 0;
Threadpool.getmaxthreads (out of Workthread, out iothread);

Get to the maximum work thread pool and IO thread pool are 200, but if according to the relevant data, said that the value of the number of *CPU (dual-core also count multiple CPUs), the Windows program to obtain a larger value, indicating that the default system to the number of threads are different.

In different. NET versions, <processmodel autoconfig= "true"/> The default configuration in Machine.config, I think it's supposed to be. NET in different versions. Information such as the default number of threads, you can modify some of the values of the node in Machine.config to achieve different purposes, the default configuration of the parameters:

Set maxworkerthreaders and Maxiothreads to 100
Set Maxconnection to 12*cpu quantity
Set minFreeThreads to 88*cpu quantity
Set minWorkerThreads to 50

Maximum number of threads = (maximum worker thread * CPU count)-minimum idle thread, and of course some other important parameters.

These are changes to the configuration files in IIS6 and IIS7 Classic mode, and the Ii7 integration mode is a bit different, and the maximum number of requests is determined by the following: Maxconcurrentrequestspercpu: Limit the number of requests per CPU to execute, even if more threads are available. In. NET 3.5 and previous versions, the default value is 12, which is 5000 in. NET 4. If set to 0, there is no limit; MAXCONCURRENTTHREADSPERCPU: Limit the number of threads per CPU processing requests. The default value is 0, with no restrictions. This is basically equivalent to the number of requests not limited, while <processmodel

requestqueuelimit= "10000"/> added.

Indicates the request queued queue 10000, set in%systemroot%system32inetsrvconfigapplicationhost.config, <serverruntime appconcurrentrequestlimit= "10000"/> To increase the parallel request limit

Look at a multithreaded operation code using the socket

The first two namespaces must be included:

Using System.Net;

Using System.Net.Sockets;

Several commonly used classes: (These things, check out MSDN is very detailed)

Iphostentry, Dns,ipaddress,ipendpoint, and the most important socket.

IPEndPoint: This is the network endpoint, well understood, is a fixed address on the network: a combination of IP and a port.

Below I still use a very simple chat program that I wrote before to do example, (very short code)

Form1.cs

Description, this is set server with the client and one.

using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Text;
Using System.Windows.Forms;
Using System.Net;
Using System.Net.Sockets; This and above are necessary to use the socket.
Using System.IO;
Using System.Threading; This is required to use multithreading.

Namespace Onlysocket
{
    public partial class form1:form     & nbsp;    //partial indicates that this code is only part of the Form1 class, Form1 class inherits from the form class
    {
         public Form1 ()
        {
             InitializeComponent ();   //constructor, initialize container.
       }
        Socket sock;          //Define an object for the socket class (default is protected)
        thread th;             //Define an object for the thread class
        //

public static IPAddress Getserverip ()//static functions that can be invoked without instantiation.
{
Iphostentry Ieh = Dns.gethostbyname (Dns.gethostname ()); No more, two static functions of the DNS class

or use Dns.resolve () instead of gethostname ()
return ieh.addresslist[0]; Returns an instance of the address class. Here AddressList is an array not surprisingly, a server with n IP is possible
}

private void Beginlisten ()//socket listener function, and so on as a parameter to create a new thread


{


IPAddress ServerIP = Getserverip (); Call this class static function Getserverip get the native IPAddress.


IPEndPoint IEP = new IPEndPoint (ServerIP, Convert.ToInt32 (Tbport.text)); Local endpoint


Sock = new Socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp); Instantiation of member Sock


byte[] Bytemessage = new byte[100]; The byte array buffer that holds the message, noting the array representation method, unlike C.


This.lbiep.text = Iep.tostring ();


Sock.bind (IEP); An important function of the socket class, binding an IP,


while (true)//Here is a dead loop to listen to the port, someone will ask the dead loop, the program is not stuck, note that this is just a class, there is no main function.


{


Try


{


Sock.listen (5); OK, sock binds the local endpoint to start listening, 5 indicates the maximum number of connections is 5.


Socket Newsock = Sock.accept (); Here is an important method for the Socket class: Accept, which accepts a socket connection request from outside and returns a socket socket, which begins to process the conversation between the client and the server


Newsock.receive (Bytemessage); Accept the data sent by the client to the buffer.


String msg = "from [" + newsock.remoteendpoint.tostring () +]: "+system.text.encoding.utf8.getstring (bytemessage) +" n "; The GetString () function converts a byte array to a string type.


Rtbtalk.appendtext (msg+ "n"); Show in Text control


}


catch (socketexception se)//catch exception,


{


Lbstate.text = Se.tostring (); To display it, you can also customize the error here.


}


}


}

Events triggered by the private void Btconnect_click (object sender, EventArgs e)//Connection button: Connection server


{


btconnect.enabled = false;


Btstopconnect.enabled = true;


Try


{


th = new Thread (new ThreadStart (Beginlisten)); Creating a new thread is specifically used to handle listening, which can be written separately, for example: ThreadStart ts=new ThreadStart (Beginlisten); Th=new thread (TS); Note, however, that the parameters of the ThreadStart constructor must be a function without parameters. This function name is actually its pointer, is this a delegate?


Th.start (); Start thread


Lbstate.text = "listenning ...";


}


catch (socketexception se)//handling Exceptions


{


MessageBox.Show (Se.message, "Problems arise", MessageBoxButtons.OK, MessageBoxIcon.Information);


}


catch (ArgumentNullException AE)//parameter is an empty exception


{


Lbstate.text = "parameter Error";


MessageBox.Show (ae.message, "error", MessageBoxButtons.OK, messageboxicon.warning);


}

}

private void Btstopconnect_click (object sender, EventArgs e)/stop listening


{


btstopconnect.enabled = false;


Btconnect.enabled = true;


Sock.close (); Close socket


Th.abort (); Terminating the listener thread





Lbstate.text = "Listenning stopped";


}

private void Btexit_click (object sender, EventArgs e)
{
Sock.close ();
Th.abort ();
Dispose (); Cleaning up resources is freeing up memory
This.close (); Closes the dialog box and exits the program
}

private void Btsend_click (object sender, EventArgs e)


{


Try


{


IPAddress ClientIP = Ipaddress.parse (Tbtargetip.text); Class IPAddress static function Parse (): Converts text to an instance of IPAddress.


int clientport = Convert.ToInt32 (Tbport.text); C # These conversion functions are very convenient, not like C + + trouble


IPEndPoint Clientiep = new IPEndPoint (ClientIP, ClientPort); It's not very good to use the client.


Byte[] Byte_message;


Socket socket = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp); There are many parameters to instantiate, this is TCP. TCP SocketType is stream: Data flow, if the protocol type is UDP, then packet transmission, QQ is the use of UDP.


Socket.connect (CLIENTIEP); Another function of the socket, connect (ipendpoint). Connect Remote sockets


Byte_message = System.text.encoding.utf8.getbytes (Rtbwords.text); Discover UTF8 can support Chinese, use it


Socket.send (Byte_message);


Rtbtalk.appendtext ("n" + "My words:" + Rtbwords.text + "n");


Socket.shutdown (Socketshutdown.both);


Socket.close ();


}


catch (ArgumentNullException AE)


{


MessageBox.Show (ae.message, "parameter is empty", messageboxbuttons.okcancel,messageboxicon.information);


}


catch (SocketException se)


{


MessageBox.Show (Se.message, "Problems arise", MessageBoxButtons.OK, MessageBoxIcon.Information);


}


}





}


}

Program.cs

using System;
Using System.Collections.Generic;
Using System.Windows.Forms;

Namespace Onlysocket
{
Static Class Program
{
<summary>
The main entry point for the application.
</summary>
[STAThread]
static void Main ()//Here is the main function

{
Application.enablevisualstyles ();
Application.setcompatibletextrenderingdefault (FALSE);
Application.Run (New Form1 ());
}
}
}


Wrote for a long time, enough tired, although are very basic things, I write when I also review the side, hehe.

In fact, multithreading I am not very skilled, I remember last summer, wrote a multithreaded scanner, also do not know why, the thread opened to more than 50 on the abnormal, very depressed. In fact, I was using the new Thread=thread (new ThreadStart (fun)) to achieve, the method feels very clumsy, hehe.

The approximate code seems to be like this:

First write a scan class:

public class scan

{

try{public Scan () {...} init ...}

public void scan{... Task Loop Scan ...} The task structure has an IP, a port, a scanned tag flag}

catch{}

}

And then the main function can do this:

Scan[] scanner = new SCAN[XX]

thread[] thread = new THREAD[XX];
for (int i = 0; i < xx;i++)
{
Scanner[i] = new Scan (this, i);
Thread[i] = new Thread (new ThreadStart (Scanner[i].startscan));
Thread[i].start ();

}

In fact, this can be a simple implementation of multithreading.

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.